绑定方法和非绑定方法
类中的方法本质是类属性,另外就是只有在所在类拥有实例时,才能调用方法。这种方法就是绑定方法,这类方法的第一个参数是self。
非绑定方法用到的地方比较少,书中举的例子是覆盖父类方法。
class EmplAddrBookEntry(AddrBookEntry): 'Employee Address Book Entry class' def __init__(self, nm, ph, em): AddrBookEntry.__init__(self, nm, ph) self.empid = id self.email = em 其中AddrBookEntry.__init__(self, nm, ph)就是非绑定方法(没有实例)。
静态方法和类方法
静态方法仅仅是类中的函数,不带self参数。
类方法同样也是不带self参数,它需要类作为第一个参数。
class TestStaticMethod: def foo(): # 静态方法 print 'calling static method foo()' foo = staticmethod(foo) class TestClassMethod: def foo(cls): # 类方法 print 'calling class method foo()' print 'foo() is part of class:', cls.__name__ foo = classmethod(foo) 用在函数那章学的装饰器表示更简洁。 class TestStaticMethod: @staticmethod def foo(): print "calling static method foo()" class TestClassMethod: @classmethod def foo(cls): print "calling class method foo()" print "foo() is part of class:", cls.__name__