对Python中的@classmethod用法详解

yipeiwu_com6年前Python基础

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

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

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

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

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()

程序的执行结果如下:

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设计】。

相关文章

详解python3中用HTMLTestRunner.py报ImportError: No module named 'StringIO'如何解决

详解python3中用HTMLTestRunner.py报ImportError: No module named 'StringIO'如何解决

python3中用HTMLTestRunner.py报ImportError: No module named 'StringIO'的解决方法: 1.原因是官网的是python2语法写的...

python实现协同过滤推荐算法完整代码示例

python实现协同过滤推荐算法完整代码示例

测试数据 http://grouplens.org/datasets/movielens/ 协同过滤推荐算法主要分为: 1、基于用户。根据相邻用户,预测当前用户没有偏好的未涉及物品...

使用python实现对元素的长截图功能

使用python实现对元素的长截图功能

一.目标 浏览网页的时候,看见哪个元素,就能截取哪个元素当图片,不管那个元素有多长   二.所用工具和第三方库 python ,PIL,selenium pycharm 三....

python实现自动更换ip的方法

本文实例讲述了python实现自动更换ip的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/env python #-*- encoding:gb2312 -*...

python合并已经存在的sheet数据到新sheet的方法

简单的合并,本例是横向合并,纵向合并可以自行调整。 import xlrd import xlwt import shutil from xlutils.copy import...