您好,登錄后才能下訂單哦!
小編給大家分享一下python中怎么使用類方法和靜態(tài)方法,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
class People: country='China' # 類方法 用classmethod來修飾 @classmethod #通過標(biāo)識符來表示下方方法為類方法 def get_country(cls): #習(xí)慣性使用cls return cls.country #訪問類屬性 pass pass print(People.get_country()) #通過類對象去引用 p=People() print('實例對象訪問%s'%p.get_country()) #通過實例對象去訪問
class People: country='China' # 類方法 用classmethod來修飾 @classmethod #通過標(biāo)識符來表示下方方法為類方法 def get_country(cls): #習(xí)慣性使用cls return cls.country #訪問類屬性 pass @classmethod def change_country(cls,data): cls.country=data #修改類屬性的值在類方法中 pass print(People.get_country()) #通過類對象去引用 p=People() print('實例對象訪問%s'%p.get_country()) People.change_country('英') print(People.get_country())
class People: country='China' # 類方法 用classmethod來修飾 @classmethod #通過標(biāo)識符來表示下方方法為類方法 def get_country(cls): #習(xí)慣性使用cls return cls.country #訪問類屬性 pass @classmethod def change_country(cls,data): cls.country=data #修改類屬性的值在類方法中 pass @staticmethod def getData(): #無需傳參數(shù) return People.country pass print(People.getData()) #可以訪問 # print(People.get_country()) #通過類對象去引用 p=People() print(People.getData()) #可以訪問 注意 一般情況下 我們不會通過實例對象去訪問靜態(tài)方法
為什么要使用靜態(tài)方法呢?
由于靜態(tài)方法主要來存放邏輯性的代碼 本身和類以及實例對象沒有交互
也就是說 在靜態(tài)方法中 不會涉及到類中方法和屬性的操作
數(shù)據(jù)資源能夠得到有效的充分利用
# demo 返回當(dāng)前的系統(tǒng)時間 import time #引入時間模塊 class TimeTest: def __init__(self,hour,min,second): self.hour=hour self.min=min self.second=second @staticmethod #直接定義為靜態(tài)方法 不需要實例屬性 def showtime(): return time.strftime('%H:%M:%S',time.localtime()) pass print(TimeTest.showtime()) t=TimeTest(2,10,15) print(t.showtime()) #無必要 直接使用靜態(tài)方法 輸出仍是導(dǎo)入時間
看完了這篇文章,相信你對“python中怎么使用類方法和靜態(tài)方法”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。