類方法
class People: country="China" # 類方法 用classmethod來修飾 @classmethod #通過標識符來表示下方方法為類方法 def get_country(cls): #習慣性使用cls return cls.country #訪問類屬性 pass pass print(People.get_country()) #通過類對象去引用 p=People() print("實例對象訪問%s"%p.get_country()) #通過實例對象去訪問
class People: country="China" # 類方法 用classmethod來修飾 @classmethod #通過標識符來表示下方方法為類方法 def get_country(cls): #習慣性使用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 #通過標識符來表示下方方法為類方法 def get_country(cls): #習慣性使用cls return cls.country #訪問類屬性 pass @classmethod def change_country(cls,data): cls.country=data #修改類屬性的值在類方法中 pass @staticmethod def getData(): #無需傳參數 return People.country pass print(People.getData()) #可以訪問 # print(People.get_country()) #通過類對象去引用 p=People() print(People.getData()) #可以訪問 注意 一般情況下 我們不會通過實例對象去訪問靜態方法
為什么要使用靜態方法呢?
由于靜態方法主要來存放邏輯性的代碼 本身和類以及實例對象沒有交互
也就是說 在靜態方法中 不會涉及到類中方法和屬性的操作
數據資源能夠得到有效的充分利用
# demo 返回當前的系統時間 import time #引入時間模塊 class TimeTest: def __init__(self,hour,min,second): self.hour=hour self.min=min self.second=second @staticmethod #直接定義為靜態方法 不需要實例屬性 def showtime(): return time.strftime("%H:%M:%S",time.localtime()) pass print(TimeTest.showtime()) t=TimeTest(2,10,15) print(t.showtime()) #無必要 直接使用靜態方法 輸出仍是導入時間
復習
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注服務器之家的更多內容!
原文鏈接:https://blog.csdn.net/weixin_44632711/article/details/120697745