python基礎(chǔ)之類方法和靜態(tài)方法
發(fā)布日期:2021-12-20 21:55 | 文章來(lái)源:源碼之家
類方法

class People:
country='China'
# 類方法 用classmethod來(lái)修飾
@classmethod #通過(guò)標(biāo)識(shí)符來(lái)表示下方方法為類方法
def get_country(cls): #習(xí)慣性使用cls
return cls.country #訪問(wèn)類屬性
pass
pass
print(People.get_country()) #通過(guò)類對(duì)象去引用
p=People()
print('實(shí)例對(duì)象訪問(wèn)%s'%p.get_country()) #通過(guò)實(shí)例對(duì)象去訪問(wèn)

class People:
country='China'
# 類方法 用classmethod來(lái)修飾
@classmethod #通過(guò)標(biāo)識(shí)符來(lái)表示下方方法為類方法
def get_country(cls): #習(xí)慣性使用cls
return cls.country #訪問(wèn)類屬性
pass
@classmethod
def change_country(cls,data):
cls.country=data #修改類屬性的值在類方法中
pass
print(People.get_country()) #通過(guò)類對(duì)象去引用
p=People()
print('實(shí)例對(duì)象訪問(wèn)%s'%p.get_country())
People.change_country('英')
print(People.get_country())

靜態(tài)方法

class People: country='China' # 類方法 用classmethod來(lái)修飾 @classmethod #通過(guò)標(biāo)識(shí)符來(lái)表示下方方法為類方法 def get_country(cls): #習(xí)慣性使用cls return cls.country #訪問(wèn)類屬性 pass @classmethod def change_country(cls,data): cls.country=data #修改類屬性的值在類方法中 pass @staticmethod def getData(): #無(wú)需傳參數(shù) return People.country pass print(People.getData())#可以訪問(wèn) # print(People.get_country()) #通過(guò)類對(duì)象去引用 p=People() print(People.getData())#可以訪問(wèn) 注意 一般情況下 我們不會(huì)通過(guò)實(shí)例對(duì)象去訪問(wèn)靜態(tài)方法

為什么要使用靜態(tài)方法呢?
由于靜態(tài)方法主要來(lái)存放邏輯性的代碼 本身和類以及實(shí)例對(duì)象沒(méi)有交互
也就是說(shuō) 在靜態(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()) #無(wú)必要 直接使用靜態(tài)方法 輸出仍是導(dǎo)入時(shí)間




復(fù)習(xí)


總結(jié)
本篇文章就到這里了,希望能夠給你帶來(lái)幫助,也希望您能夠多多關(guān)注本站的更多內(nèi)容!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
相關(guān)文章
關(guān)注官方微信