• 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
    
    

  • 相关阅读:
    【leetcode 461】. Hamming Distance
    【leetcode 476】. Number Complement
    大数据概述
    对于编译原理的看法
    PHP基础(二) 文件包含
    PHP基础(一)
    webpack 之(6) commonJS和 ES6 Module区别 (未完成)
    webpack 之(5) webpack.config.js配置 之 img
    webpack 之(4) webpack.config.js配置 之 html
    webpack 之(3) webpack.config.js配置 之 css/less
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13349212.html
Copyright © 2020-2023  润新知