13.8.1 staticmethod()和 classmethod()内建函数
现在让我们看一下在经典中创建静态方法和类方法的一些例子(你也可以把它们用在新式类中):
class TestStaticMethod:
def foo():
print 'calling static method foo()'
# foo=staticmethod(foo)
print TestStaticMethod.foo()
C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/eeeee/a5.py
Traceback (most recent call last):
File "C:/Users/TLCB/PycharmProjects/untitled/eeeee/a5.py", line 5, in <module>
print TestStaticMethod.foo()
TypeError: unbound method foo() must be called with TestStaticMethod instance as first argument (got nothing instead)
class TestStaticMethod:
def foo():
print 'calling static method foo()'
foo=staticmethod(foo)
print TestStaticMethod.foo()
C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/eeeee/a5.py
calling static method foo()
None
类方法:
class TestClassMethod:
def foo(cls):
print cls
print 'calling class method foo()'
print 'foo() is part of class:', cls.__name__
foo = classmethod(foo)
print TestClassMethod.foo()
C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/eeeee/a5.py
__main__.TestClassMethod
calling class method foo()
foo() is part of class: TestClassMethod
None
实例方法:
class TestClassMethod:
def foo(self):
print self
a=TestClassMethod()
print a.foo()
C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/eeeee/a5.py
<__main__.TestClassMethod instance at 0x025AF490>
None