当一个类中有多个__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