python classmethod_对Python中的@classmethod用法详解
在Python面向?qū)ο缶幊讨械念悩?gòu)建中,有時候會遇到@classmethod的用法。
總感覺有這種特殊性說明的用法都是高級用法,在我這個層級的水平中一般是用不到的。
不過還是好奇去查了一下。
大致可以理解為:使用了@classmethod修飾的方法是類專屬的,而且是可以通過類名進行調(diào)用的。為了能夠展示其與一般方法的差異,寫一段簡單的代碼如下:
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()
程序的執(zhí)行結(jié)果如下:
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
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
DemoClass.objPrint()
TypeError:objPrint() missing 1 required positional argument: 'self'
上面的程序執(zhí)行,我是在兩個操作系統(tǒng)中的兩個Python版本環(huán)境中進行的。不管是Py2還是Py3,這方面的設(shè)計都是差不多的。總體來說,這種用法還是很微妙的。由于沒有足夠的實戰(zhàn)歷練,暫時還說不好這個東西有什么更好的優(yōu)勢。
這篇對Python中的@classmethod用法詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
總結(jié)
以上是生活随笔為你收集整理的python classmethod_对Python中的@classmethod用法详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 传值类型_java中的“传值”与“传址”
- 下一篇: python计算函数运行时间表_pyth