zoukankan      html  css  js  c++  java
  • python3 classmethod

    classmethod是用来指定一个类的方法为类方法,没有此参数指定的类的方法为实例方法,使用方法如下

    class C:
        @classmethod
        def f(cls, arg1, arg2, ...): ...
    

    类方法既可以直接类调用 C.f()

    也可以进行实例调用 C().f()

    具体实现:

    >>> class C:
    ...     @classmethod
    ...     def f(self):
    ...             print "This is a class method"
    ...
    >>> C.f()
    This is a class method
    >>> c = C()
    >>> c.f()
    This is a class method
    >>> class D:
    ...     def f(self):
    ...             print " This is not a class method "
    ...
    >>> D.f()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unbound method f() must be called with D instance as first argument (got nothing instead)
    >>> d = D()
    >>> d.f()
    This is not a class method
    
  • 相关阅读:
    设计模式
    python高亮显示输出
    数据库入门3 数据库设计
    分支循环相关
    软件目录结构规范
    数据库入门2 数据库基础
    三级菜单
    字符串相关问题
    登录接口
    购物车
  • 原文地址:https://www.cnblogs.com/xp1005/p/6565672.html
Copyright © 2011-2022 走看看