您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

python函数之classmethod()

2024/6/30 18:51:25发布39次查看
classmethod(function)中文说明:
classmethod是用来指定一个类的方法为类方法,没有此参数指定的类的方法为实例方法,使用方法如下:
class c: @classmethod def f(cls, arg1, arg2, ...): ...

类方法既可以直接类调用(c.f()),也可以进行实例调用(c().f())。
版本:python2.2中新增,在python2.4中增加新功能。python3中仍可用。
英文说明:
return a class method for function.
a class method receives the class as implicit first argument, just like an instance method receives the instance. to declare a class method, use this idiom:
class c: @classmethod def f(cls, arg1, arg2, ...): ...

the @classmethod form is a function decorator – see the description of function definitions in function definitions for details.
it can be called either on the class (such as c.f()) or on an instance (such as c().f()). the instance is ignored except for its class. if a class method is called for a derived class, the derived class object is passed as the implied first argument.
class methods are different than c++ or java static methods. if you want those, see staticmethod() in this section.
for more information on class methods, consult the documentation on the standard type hierarchy in the standard type hierarchy.
new in version 2.2.
changed in version 2.4: function decorator syntax added.
代码实例:
>>> 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函数之classmethod()的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product