我使用的是python3.6,希望编写一个扩展datatime.date
的类,并在代码中引入一些我需要的附加属性和方法。
问题是,由于似乎太多的参数,初始化似乎无法正常工作。在
以下是最低限度的代码:
FORMAT__DD_MM_YYYY = "dd.mm.yyyy"
from datetime import date
class DateExtended(date):
date_string = None
date_format = None
def __init__(self, year: int, month: int, day: int, date_format: str=None):
super().__init__(year=year, month=month, day=day)
self.date_format = date_format
self.date_string = "{:02d}.{:02d}.{:04d}".format(self.day, self.month, self.year)
bla1 = DateExtended(year=2010, month=5, day=3, date_format=FORMAT__DD_MM_YYYY_DOT)
执行它会导致以下错误:
^{pr2}$我在这里做错了什么?应该如何解决?在
是因为date
没有扩展object
?在
旁注:当我自己尝试修复这个问题时,我还编写了一个不同的类,它不是从date
继承的,而是创建一个date
对象并将其作为其属性之一存储:
self.date = date(year=year, month=month, day=day)
没有遇到任何问题。在
这是因为}只接受3个参数,而不是4个参数。在
datetime.date
在__new__
中进行初始化,而不是在__init__
中初始化,而错误来自于{因此您还必须重写
__new__
:相关问题 更多 >
编程相关推荐