![](/img/trans.png)
[英]Why can't pass *args and **kwargs in __init__ of a child class
[英]Inherit from a built-in class, can't change args of __init__
我使用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或更改方法?
date类是一个不可变的对象,因此您需要改写__new__()
静态方法 :
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.