0

我创建了一个具有date对象继承的类,但我无法更改应该提供给__init__.

>>> class Foo(date):
...  def __init__(self,y,m=0,d=0):
...     date.__init__(self,y,m,d)
... 
>>> Foo(1,1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Required argument 'day' (pos 3) not found

我已经尝试使用super...

如果有人知道我们是否可以更改内置对象 args 或这样做的方式?

4

1 回答 1

4

日期类是一个不可变对象,因此您需要重写__new__()静态方法

class Foo(date):
    def __new__(cls, year, month=1, day=1):
        return super(Foo, cls).__new__(cls, year, month, day)

请注意,您至少需要将月份和日期设置为1,0month不是andday参数的允许值。

使用__new__作品:

>>> class Foo(date):
...     def __new__(cls, year, month=1, day=1):
...         return super(Foo, cls).__new__(cls, year, month, day)
... 
>>> Foo(2013)
Foo(2013, 1, 1)
于 2013-03-28T17:04:54.267 回答