python基礎(chǔ)之類方法和靜態(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())

靜態(tài)方法

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)入時間




復(fù)習(xí)


總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
如何使用Flask-Migrate拓展數(shù)據(jù)庫表結(jié)構(gòu)
這篇文章主要介紹了如何使用Flask-Migrate拓展數(shù)據(jù)庫表結(jié)構(gòu),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-07-07
Python實現(xiàn)監(jiān)控鍵盤鼠標(biāo)操作示例【基于pyHook與pythoncom模塊】
這篇文章主要介紹了Python實現(xiàn)監(jiān)控鍵盤鼠標(biāo)操作,結(jié)合實例形式分析了Python基于pyHook與pythoncom模塊的鍵盤、鼠標(biāo)事件響應(yīng)及日志文件操作相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2018-09-09
pycharm專業(yè)版遠程登錄服務(wù)器的詳細(xì)教程
這篇文章主要介紹了pycharm專業(yè)版遠程登錄服務(wù)器的詳細(xì)教程,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09
pip安裝庫報錯[notice]?A?new?release?of?pip?available:?22.2
這篇文章主要給大家介紹了關(guān)于pip安裝庫報錯[notice]?A?new?release?of?pip?available:?22.2?->?22.2.2的相關(guān)資料,文中通過圖文將解決的方法介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03

