可以直接被类或者类的实例调用。
1)静态方法无需传入self参数,类成员方法需传入代表本类的cls参数;
2)从第1条,静态方法是无法访问实例变量的,而类成员方法也同样无法访问实例变量,但可以访问类变量;
3)静态方法有点像函数工具库的作用,而类成员方法则更接近类似Java面向对象概念中的静态方法。
class MyClass: val1 = ‘apple‘ def __init__(self): val2 = ‘banana‘ @staticmethod def staticmd(): print val1+":"+val2 @classmethod def classmd1(cls): print cls.val2 @classmethod def classmd2(cls): print cls.val1
>>> MyClass.staticmd() --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-325-e7a1dcd0e04d> in <module>() ----> 1 MyClass.staticmd() <ipython-input-323-d82dece8064f> in staticmd() 5 @staticmethod 6 def staticmd(): ----> 7 print val1+":"+val2 8 @classmethod 9 def classmd(cls): NameError: global name ‘val1‘ is not defined
>>> MyClass.classmd1() --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-327-c83635b87838> in <module>() ----> 1 MyClass.classmd1() <ipython-input-326-48fb9fb0f284> in classmd1(cls) 8 @classmethod 9 def classmd1(cls): ---> 10 print cls.val2 11 @classmethod 12 def classmd2(cls): AttributeError: class MyClass has no attribute ‘val2‘ >>> MyClass.classmd2() apple
静态方法:无法访问类属性、实例属性,相当于一个相对独立的方法,跟类其实没什么关系,换个角度来讲,其实就是放在一个类的作用域里的函数而已。
类成员方法:可以访问类属性,无法访问实例属性。上述的变量val1,在类里是类变量,在实例中又是实例变量,所以容易混淆。