从内置类继承,不能改变__init__的args

时间:2013-03-28 17:01:16

标签: python class date python-2.7 python-datetime

我创建了一个具有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或方法吗?

1 个答案:

答案 0 :(得分:4)

日期类是不可变的对象,因此您需要覆盖__new__() static method而不是:

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

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

使用__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)