码迷,mamicode.com
首页 > 编程语言 > 详细

python3 classmethod

时间:2017-03-17 14:35:41      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:first   使用方法   type   got   most   参数   unbound   python3   nbsp   

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

 

python3 classmethod

标签:first   使用方法   type   got   most   参数   unbound   python3   nbsp   

原文地址:http://www.cnblogs.com/xp1005/p/6565672.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!