【问题标题】:Inherit from a built-in class, can't change args of __init__从内置类继承,不能改变 __init__ 的参数
【发布时间】:2013-03-28 17:01:15
【问题描述】:

我使用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 或更改方法?

【问题讨论】:

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


    【解决方案1】:

    日期类是一个不可变对象,所以你需要改写__new__() static method:

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

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

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

    【讨论】:

      猜你喜欢
      • 2011-07-30
      • 2012-06-26
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 2012-05-16
      • 2011-09-26
      • 2020-04-28
      • 1970-01-01
      相关资源
      最近更新 更多