【问题标题】:Inheriting from a class (datetime.date) causes a super().__init__(...) too many arguments TypeError从类 (datetime.date) 继承会导致 super().__init__(...) 参数过多 TypeError
【发布时间】:2018-02-09 09:24:07
【问题描述】:

我正在使用 Python 3.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)

执行它会导致以下错误:

bla1 = DateExtended(year=2010, month=5, day=3, date_format=FORMAT__DD_MM_YYYY_DOT)
TypeError: function takes at most 3 arguments (4 given)

我在这里做错了什么,应该如何解决?

是不是因为date 没有扩展object


旁注:当我自己尝试解决这个问题时,我还编写了一个不同的类,它不继承自 date,而是创建一个 date 对象并将其存储为它的属性之一:

self.date = date(year=year, month=month, day=day)

没有遇到任何问题。

【问题讨论】:

  • 是的,问题是date 是一个方法,而不是一个类。你只能用另一个类来扩展一个类,而不是方法。
  • @campovski:type(date)<class 'type'>。对我来说看起来像一门课
  • @Billy 感谢您提出这个问题,但您不理解type() 的输出。 date 的类型为 type。试试type(2),你会得到<class 'int'>
  • @campovski date 是一个类。试试inspect.isclass(date)。如果date 是一个函数/方法,我的回答也不起作用。 :)
  • @MSeifert 哎呀,我的错……我想工作让我筋疲力尽……你值得点赞! :D

标签: python python-3.x class inheritance super


【解决方案1】:

这是因为datetime.date__new__ 中进行初始化,而不是在__init__ 中进行初始化,错误来自datetime.date.__new__ 只接受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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    • 2018-11-06
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    相关资源
    最近更新 更多