• 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: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
    
    

  • 相关阅读:
    矩阵价值和
    排列组合问题
    X国的军队
    石子合并加强版
    P1042 乒乓球
    Dinner 点餐
    一文看尽图像分类问题
    [Udemy] Recommender Systems and Deep Learning in Python
    推荐系统学习
    [NLP] 酒店名归类
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13349212.html
Copyright © 2020-2023  润新知