您好,登錄后才能下訂單哦!
如下所示:
class Date: def __init__(self, year, month, day): self.year = year self.month = month self.day = day # 實(shí)例方法 def tomorrow(self): self.day +=1 def __str__(self): return '{}/{}/{}'.format(self.year,self.month,self.day) # 靜態(tài)方法 @staticmethod def format_date_str(date_str): year, month, day = tuple(date_str.split('-')) return Date(int(year),int(month),int(day)) # 類方法 # 這里的 cls 實(shí)際就是類本身,它將自己本身返回,不需要我們寫(xiě)返回的類名,更好一些 @classmethod def format_str(cls, date_str): year, month, day = tuple(date_str.split('-')) return cls(int(year),int(month),int(day)) if __name__ == "__main__": new = Date(2018,12,12) print(new) new.tomorrow() print(new) # 現(xiàn)在我們想輸入一個(gè)日期字符串需要怎么做呢? date_str = '2018-12-30' year, month, day = tuple(date_str.split('-')) # 這里利用了tuple的拆包屬性,將分開(kāi)的列表分別賦給變量 new = Date(year,month,day) print(new) # 如果有靜態(tài)方法,就會(huì)更加簡(jiǎn)單了 new = Date.format_date_str('2019-12-01') print(new) # 但是靜態(tài)方法還要將類的名稱返回,那有沒(méi)有更好的方法呢 # 那就是類方法,類方法的原理就是 將輸入的參數(shù)處理后 通過(guò)類方法返回一個(gè)實(shí)例對(duì)像,靜態(tài)方法也是如此,但靜態(tài)方法可以不返回實(shí)例 而返回其他的 new = Date.format_str('2019-9-01') print(new) # 那么問(wèn)題來(lái)了?什么使用用靜態(tài)方法,什么時(shí)候使用類方法呢? # 原則上是:當(dāng)需要返回實(shí)例時(shí)使用類方法,不需要返回實(shí)例對(duì)象時(shí) 直接使用靜態(tài)方法就好了, # 例如我們做驗(yàn)證日期字符串是否合法的時(shí)候沒(méi)必要返回實(shí)例,那就使用 靜態(tài)方法就可以了
以上這篇關(guān)于Python3 類方法、靜態(tài)方法新解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。