静态方法和成员方法分别在创建时分别被装入Staticmethod 类型和 Classmethod类型的对象中。静态方法的定义没有 self参数,且能够被类本身直接调用,类方法在定义时需要名为 cls的类似于self的参数,类成员方法可以直接用类的具体对象调用。但cls参数是自动被绑定到类的,请看下面例子:
1 __metaclass__ = type 2 3 class Myclass: 4 5 def smeth(): 6 print "This is a static method" 7 smeth = staticmethod(smeth) 8 9 def cmeth(cls): 10 print "This is a class method of", cls 11 cmeth = classmethod(cmeth)
1 __metaclass__ = type 2 3 class Myclass: 4 5 @staticmethod 6 def smeth(): 7 print "This is a static method" 8 9 @classmethod 10 def cmeth(cls): 11 print "This is a class method of", cls
>>>Myclass.smeth()
This is a static method
>>>Myclass.cmeth()
This is a class method of <class '__main__.Myclass'>