定義:在類里面把一個方法綁定給類,說白了類方法是給類用的,該方法由裝飾器@classmethod所裝飾,類.綁定
到類的方法(),會把類本身當做第一個參數自動傳給綁定到類的方法中。
classA:#創建父類
x=1
@classmethod#使用裝飾器,變為類的綁定方法
deftest(cls):#定義了類的方法
print(cls,cls.x)#拿掉一個類的內存地址后,就可以實例化或者引用類的屬性了
classB(A):#子類B,B中沒有test類的綁定方法,就去父類中找,并將類名當第一個位置參數自動傳到方法里
x=2
B.test()#調用test類的綁定方法
print(B.test)#查看B.test的屬性
-------------輸出結果----------------
2
>#test是A的綁定方法,這里B繼承了
應用場景:
classDate:
def__init__(self,year,month,day):
self.year=year
self.month=month
self.day=day
@classmethod
defnow(cls):
t=time.localtime()
obj=cls(t.tm_year,t.tm_mon,t.tm_mday)
returnobj
@classmethod
deftomorrow(cls):
t=time.localtime(time.time()+86400)
obj=cls(t.tm_year,t.tm_mon,t.tm_mday)
returnobj
classEuroDate(Date):#__str__,打印由這個類產生的對象時,會觸發執行
def__str__(self):#定義在類內部,必須返回一個字符串類型
return"年:%s,月:%s,日:%s"%(self.year,self.month,self.day)
e1=EuroDate(2016,12,13)#實例化對象e1
print(e1)
e2=EuroDate.now()#調用類的綁定方法,并賦值給e2
print(e2)#打印返回結果
e3=EuroDate.tomorrow()#調用類的綁定方法,并賦值給e3
print(e3)#打印返回結果
print(EuroDate.now)#查看數據類型
print(EuroDate.tomorrow)#查看數據類型
以上內容為大家介紹了python類方法,希望對大家有所幫助,如果想要了解更多Python相關知識,請關注IT培訓機構:千鋒教育。