从类继承(日期时间.日期)导致一个super()。\uu init_u(…)太多参数类型e

2024-10-03 04:36:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是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)

没有遇到任何问题。在


Tags: 代码selfnoneformatdate属性yeardd
1条回答
网友
1楼 · 发布于 2024-10-03 04:36:16

这是因为datetime.date__new__中进行初始化,而不是在__init__中初始化,而错误来自于{}只接受3个参数,而不是4个参数。在

因此您还必须重写__new__

FORMAT__DD_MM_YYYY = "dd.mm.yyyy"
from datetime import date


class DateExtended(date):
    date_string = None
    date_format = None

    def __new__(cls, year: int, month: int, day: int, date_format: str=None):
        # because __new__ creates the instance you need to pass the arguments
        # to the superclass here and **not** in the __init__
        return super().__new__(cls, year=year, month=month, day=day)

    def __init__(self, year: int, month: int, day: int, date_format: str=None):
        # datetime.date.__init__ is just object.__init__ so it takes no arguments.
        super().__init__()  
        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)

相关问题 更多 >