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...

組み込みオブジェクトの引数を変更できるかどうか、またはその方法を誰かが知っている場合は?

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に設定する必要があることに注意してください。0 はmonthおよびday引数の許容値ではありません。

使用__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 に答える