替代建構子
Python 也允許你定義類別的「方法」,做法是使用 @classmethod 裝飾器,以及特別的第一個參數 cls。類別方法的主要用途,是定義那些會回傳該類別實例、但不使用 __init__() 相同程式碼的建構流程。
例如,你正在開發一個時間序列套件,並想自訂一個處理日期的類別 BetterDate。這個類別的屬性包括 year、month 和 day。你希望有一個建構子,可以依照 year、month、day 的數值建立 BetterDate 物件,同時也能從像是 2020-04-30 這樣的字串建立 BetterDate 物件。
下列函式可能會對你有幫助:
.split("-")方法會以"-"將字串切成陣列,例如"2020-04-30".split("-")會回傳["2020", "04", "30"],int()會把字串轉成數字,例如int("2019")會得到2019。
本練習屬於課程
Python 物件導向程式設計
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
class BetterDate:
# Constructor
def __init__(self, year, month, day):
# Recall that Python allows multiple variable assignments in one line
self.year, self.month, self.day = year, month, day
# Define a class method from_str
____
def from_str(____, datestr):
# Split the string at "-" and convert each part to integer
parts = datestr.split("-")
year, month, day = int(parts[0]), ____, ____
# Return the class instance
____ ____(____, ____, ____)
bd = BetterDate.from_str('2020-04-30')
print(bd.year)
print(bd.month)
print(bd.day)