Python中@classmethod和@staticmethod的区别
作者:Python热爱者
本文主要介绍了Python中@classmethod和@staticmethod的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
1.@classmethod
- class method是和类绑定的方法,不是和类的对象(实例)绑定的方法
- class method能够访问类的状态,因为它可以接受一个指向类的参数(cls),而不是指向类实例的参数(self)。
- class method可以修改类的状态,并应用到所有的类实例上。
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 method也是和类绑定的方法,不是和类的对象(实例)绑定
- class method不能访问类的状态
- class method存在于类中是因为它是一个相关的函数
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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!