13.8.1 staticmethod()和 classmethod()内建函数
13.8.1 staticmethod()和 classmethod()内建函数

现在让我们看一下在经典中创建静态方法和类方法的一些例子(你也可以把它们用在新式类中):

class TestStaticMethod:
  def foo():
    print 'calling static method foo()'
  # foo=staticmethod(foo)
print TestStaticMethod.foo()


C:\Python27\python.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:\Python27\python.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:\Python27\python.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:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/eeeee/a5.py
<__main__.TestClassMethod instance at 0x025AF490>
None


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

13.8.1 staticmethod()和 classmethod()内建函数

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭