日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python classmethod_对Python中的@classmethod用法详解

發布時間:2024/7/23 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python classmethod_对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

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'

上面的程序執行,我是在兩個操作系統中的兩個Python版本環境中進行的。不管是Py2還是Py3,這方面的設計都是差不多的??傮w來說,這種用法還是很微妙的。由于沒有足夠的實戰歷練,暫時還說不好這個東西有什么更好的優勢。

這篇對Python中的@classmethod用法詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

總結

以上是生活随笔為你收集整理的python classmethod_对Python中的@classmethod用法详解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。