python 類方法、靜態方法和實例方法
class Date:
# 構造函數
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def tomorrow(self):
# 實例方法
# 只實現實例方法,暫時忽略處理邏輯
pass
@staticmethod
def parse_from_string(date_str):
# 靜態方法不須要傳入對象self和類自己cls,因此當須要返回時,須要指定類名稱
# 因此就有一個缺點,當類名稱改變時,return的類名稱就須要跟着修改
# 因此在此基礎上有了另外一外解決方式: 類方法
year, month, day = tuple(date_str.split('-'))
return Date(year, month, day)
@staticmethod
def valid_str(date_str):
# 忽略處理邏輯,這裏只是爲了說明靜態方法的用途
year, month, day = tuple(date_str.split('-'))
if int(year) > 0 and (int(month) > 0 and int(month) <= 12) and (int(day) > 0 and int(day) <= 31):
return True
else:
return False
@classmethod
def from_string(cls, date_str):
# 傳入一個class, 無論類名稱如何改變,都不會受影響
# 因此類方法,彌補了上面所說的靜態方法的不足
# 這是否是意味着不須要靜態方法了?
# 並非
# 好比: 當只須要驗證字符串是否合法時,沒有調用到類,這種狀況用靜態方法,就不會有任何問題。如上面的valid_str方法
year, month, day = tuple(date_str.split('-'))
return cls(year, month, day)
def __str__(self):
return F"{self.year}/{self.month}/{self.day}"
if __name__ == '__main__':
new_day = Date("2018", "12", "31")
# 調用實例方法
new_day.tomorrow()
print(new_day)
# 當類中沒有處理 "2018-12-31" 這種參數時,須要在外部處理好後,傳入到類中
date_str = "2018-12-31"
year, month, day = tuple(date_str.split("-"))
new_day = Date(int(year), int(month), int(day))
print(new_day)
# 用staticmethod(靜態方法)完成初始化
new_day = Date.parse_from_string(date_str)
print(new_day)
# 用classmethod(類方法)完成初始化
new_day = Date.from_string(date_str)
print(new_day)