扣丁学堂Python培训浅谈Python中的@classmethod用法

2018-07-10 13:48:42 506浏览

本篇文章扣丁学堂Python培训小编和大家分享一下Python中的@classmethod用法,对Python开发感兴趣的小伙伴下面就随着小编一起来看一下吧。



扣丁学堂Python培训浅谈Python中的@classmethod用法



在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在线学习小编给大家分享的对Python中的@classmethod用法详解,希望对小伙伴们有所帮助,想要了解更多内容的小伙伴可以登录扣丁学堂官网咨询。扣丁学堂有专业的Python培训班供大家学习,不仅有时俱进的课程体系还有专业的老师授课,定能让你轻松学习,高薪就业。扣丁学堂Python技术交流群:279521237。




扣丁学堂微信公众号

关注微信公众号获取更多学习资料



查看更多关于"Python开发资讯"的相关文章>


标签: 扣丁学堂Python培训 Python中的@classmethod用法 Python培训 Python视频教程 Python基础教程 python安装教程 Python核心编程 Python在线教程 Python在线视频 Python在线学习

热门专区

暂无热门资讯

课程推荐

微信
微博
15311698296

全国免费咨询热线

邮箱:codingke@1000phone.com

官方群:148715490

北京千锋互联科技有限公司版权所有   北京市海淀区宝盛北里西区28号中关村智诚科创大厦4层
京ICP备12003911号-6   Copyright © 2013 - 2019

京公网安备 11010802030908号