python基礎(chǔ)之類方法和靜態(tài)方法
類方法
class People: country='China' # 類方法 用classmethod來修飾 @classmethod #通過標(biāo)識(shí)符來表示下方方法為類方法 def get_country(cls): #習(xí)慣性使用cls return cls.country #訪問類屬性 pass pass print(People.get_country()) #通過類對(duì)象去引用 p=People() print('實(shí)例對(duì)象訪問%s'%p.get_country()) #通過實(shí)例對(duì)象去訪問
class People: country='China' # 類方法 用classmethod來修飾 @classmethod #通過標(biāo)識(shí)符來表示下方方法為類方法 def get_country(cls): #習(xí)慣性使用cls return cls.country #訪問類屬性 pass @classmethod def change_country(cls,data): cls.country=data #修改類屬性的值在類方法中 pass print(People.get_country()) #通過類對(duì)象去引用 p=People() print('實(shí)例對(duì)象訪問%s'%p.get_country()) People.change_country('英') print(People.get_country())
靜態(tài)方法
class People: country='China' # 類方法 用classmethod來修飾 @classmethod #通過標(biāo)識(shí)符來表示下方方法為類方法 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()) #通過類對(duì)象去引用 p=People() print(People.getData()) #可以訪問 注意 一般情況下 我們不會(huì)通過實(shí)例對(duì)象去訪問靜態(tài)方法
為什么要使用靜態(tài)方法呢?
由于靜態(tài)方法主要來存放邏輯性的代碼 本身和類以及實(shí)例對(duì)象沒有交互
也就是說 在靜態(tài)方法中 不會(huì)涉及到類中方法和屬性的操作
數(shù)據(jù)資源能夠得到有效的充分利用
# demo 返回當(dāng)前的系統(tǒng)時(shí)間 import time #引入時(shí)間模塊 class TimeTest: def __init__(self,hour,min,second): self.hour=hour self.min=min self.second=second @staticmethod #直接定義為靜態(tài)方法 不需要實(shí)例屬性 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)入時(shí)間
復(fù)習(xí)
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
python實(shí)現(xiàn)二叉查找樹實(shí)例代碼
這篇文章主要介紹了python實(shí)現(xiàn)二叉查找樹實(shí)例代碼,分享了相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02如何使用Flask-Migrate拓展數(shù)據(jù)庫表結(jié)構(gòu)
這篇文章主要介紹了如何使用Flask-Migrate拓展數(shù)據(jù)庫表結(jié)構(gòu),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07Python實(shí)現(xiàn)監(jiān)控鍵盤鼠標(biāo)操作示例【基于pyHook與pythoncom模塊】
這篇文章主要介紹了Python實(shí)現(xiàn)監(jiān)控鍵盤鼠標(biāo)操作,結(jié)合實(shí)例形式分析了Python基于pyHook與pythoncom模塊的鍵盤、鼠標(biāo)事件響應(yīng)及日志文件操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-09-09pycharm專業(yè)版遠(yuǎn)程登錄服務(wù)器的詳細(xì)教程
這篇文章主要介紹了pycharm專業(yè)版遠(yuǎn)程登錄服務(wù)器的詳細(xì)教程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09pip安裝庫報(bào)錯(cuò)[notice]?A?new?release?of?pip?available:?22.2
這篇文章主要給大家介紹了關(guān)于pip安裝庫報(bào)錯(cuò)[notice]?A?new?release?of?pip?available:?22.2?->?22.2.2的相關(guān)資料,文中通過圖文將解決的方法介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03Python實(shí)現(xiàn)GIF動(dòng)圖以及視頻卡通化詳解
本文主要介紹了如何使用Python中的animegan2-pytorch實(shí)現(xiàn)動(dòng)圖以及視頻的卡通化效果,文中的代碼具有一定的學(xué)習(xí)價(jià)值,需要的朋友可以參考一下2021-12-12