小編給大家分享一下python中怎么使用類方法和靜態方法,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

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()) #無必要 直接使用靜態方法 輸出仍是導入時間





看完了這篇文章,相信你對“python中怎么使用類方法和靜態方法”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。