python函数之classmethod()


本文摘自php中文网,作者巴扎黑,侵删。

classmethod(function)

中文说明:

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

1

2

3

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:

1

2

3

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.

代码实例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

>>> 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()的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python如何实现单例模式

Python中什么是算术运算符、赋值运算符和复合运算符?

Python使用正则表达式连接符的示例代码

详解介绍Python的发展起源及基础知识

成为Python大牛必不可少的几款编辑器

Python怎么调用api实现智能回复功能

Python安装路径怎么找

详细分析之Python可变对象和不可变对象

Python需要什么软件

Python编程工具有哪些

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...