當一個類中有多個__init__
方法時,執行代碼會報錯;也就是說一個類中采用__init__方法來實現定義多個構造器時不可取的
class My_Date():
def __init__(self,year,month,day):
#指定的年月日
self.year=year
self.month=month
self.day=day
def __init__(self,year,month):
self.year = year
self.month = month
if __name__ == '__main__':
d=My_Date(2022,8,2)
print(d)
報錯:TypeError: init() takes 3 positional arguments but 4 were given
from datetime import datetime,timedelta
class My_Date1:
def __init__(self,year,month,day):
self.year=year
self.month=month
self.day=day
def run(self):
return 'working'
@classmethod
def today(cls):
now_time=datetime.now()
return cls(now_time.year,now_time.month,now_time.day)
if __name__ == '__main__':
my_date=My_Date1(2022,12,12)
print(my_date)
print(my_date.run())
t=My_Date1.today()
print(t)
print(t.year)
print(t.day)
print(t.run())
執行結果:
<main.My_Date1 object at 0x0000026C0986ED00>
working
<main.My_Date1 object at 0x0000026C0986ECA0>
2022
3
working