Python中的@classmethod


本文摘自php中文网,作者不言,侵删。

下面为大家分享一篇对Python中的@classmethod用法详解,具有很好的参考价值,希望对大家有所帮助。一起过来看看吧

在Python面向对象编程中的类构建中,有时候会遇到@classmethod的用法。

总感觉有这种特殊性说明的用法都是高级用法,在我这个层级的水平中一般是用不到的。

不过还是好奇去查了一下。

大致可以理解为:使用了@classmethod修饰的方法是类专属的,而且是可以通过类名进行调用的。为了能够展示其与一般方法的差异,写一段简单的代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

class DemoClass:

    @classmethod

    def classPrint(self):

       print("class method")

    def objPrint(self):

       print("obj method")

  

obj = DemoClass()

obj.objPrint()

obj.classPrint()

  

DemoClass.classPrint()

DemoClass.objPrint()

程序的执行结果如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

grey@DESKTOP-3T80NPQ:/mnt/e/01_workspace/02_programme_language/03_python/03_OOP/2017/08$python classmethod.py

obj method

class method

class method

Traceback (mostrecent call last):

 File "classmethod.py", line 13, in<module>

  DemoClass.objPrint()

TypeError: unboundmethod objPrint() must be called with DemoClass instance as first argument (gotnothing instead)

grey@DESKTOP-3T80NPQ:/mnt/e/01_workspace/02_programme_language/03_python/03_OOP/2017/08$exit

exit

  

E:\01_workspace\02_programme_language\03_python\03_OOP\2017\08>pythonclassmethod.py

obj method

class method

class method

Traceback (mostrecent call last):

 File "classmethod.py", line 13, in<module>

  DemoClass.objPrint()

TypeError:objPrint() missing 1 required positional argument: 'self'

上面的程序执行,我是在两个操作系统中的两个Python版本环境中进行的。不管是Py2还是Py3,这方面的设计都是差不多的。总体来说,这种用法还是很微妙的。由于没有足够的实战历练,暂时还说不好这个东西有什么更好的优势。

相关推荐:

python函数之classmethod()


以上就是Python中的@classmethod的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python的format函数是什么意思

简述Python如何调用系统底层api播放wav文件

Python切片索引用法

Python可以做动图吗

初学Python 请教学习路线

Python中_和__的区别是什么

Python中index怎么用

Python cookbook(字符串与文本)针对任意多的分隔符拆分字符串操作

零基础可以学习Python中的爬虫知识吗?(新手必看)

Python需要有编程的基础吗

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




打赏

取消

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

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

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

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

评论

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