python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python @classmethod和@staticmethod

Python中@classmethod和@staticmethod的区别

作者:Python热爱者

本文主要介绍了Python中@classmethod和@staticmethod的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

1.@classmethod

class C(object):
    @classmethod
    def fun(cls, arg1, arg2, ...):
       ....
fun: function that needs to be converted into a class method
returns: a class method for function.

2.@staticmethod

class C(object):
    @staticmethod
    def fun(arg1, arg2, ...):
        ...
returns: a static method for function fun.

3.例子

class A(object):
    value = 42
    
    def m1(self):
        print(self.value)

    @classmethod
    def m2(cls):
        print(cls.value)
        cls.value += 10

    @staticmethod
    def m3(cls_instance):
        cls_instance.value -= 10

#小编创建了一个Python学习交流群:531509025
a = A() # 
a.m1 # <bound method A.m1 of <__main__.A object at 0x7fc8400b7da0>>
a.m1() # 42
# m1()是类A中的普通方法,必须在实例化的对象上进行调用。如果使用直接A.m1()就会得到m1() missing 1 required positional argument: 'self'的错误信息。

到此这篇关于Python中@classmethod和@staticmethod的区别的文章就介绍到这了,更多相关Python @classmethod和@staticmethod内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文