溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

關(guān)于Python3 類方法、靜態(tài)方法新解

發(fā)布時(shí)間:2020-10-11 02:24:05 來(lái)源:腳本之家 閱讀:142 作者:haeasringnar 欄目:開(kāi)發(fā)技術(shù)

如下所示:

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è)參考,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)
AI