سؤال

I make a class with date objects inheritance, but I can't change arguments which should be give to __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

I already try to use super...

If someone know if we can change builtin objects args or the way to do it ?

هل كانت مفيدة؟

المحلول

The date class is a immutable object, so you need to override the __new__() static method instead:

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

Note that you need to set the month and day to 1 at least, 0 is not a permissible value for the month and day arguments.

Using __new__ works:

>>> 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)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top