我正在尝试创建一个继承自一个str
类型和第二个类的派生类。这是有问题的,因为str
类型不只是调用__init__
,而是__new__
由于其不变性而导致的方法。我知道 for__init__
和 super 要正常工作,您需要一直使用相同的调用结构。但是,以下实现失败:
class base(object):
def __new__(cls, *args, **kwargs):
print "NEW BASE:", cls, args, kwargs
return super(base, cls).__new__(cls, *args, **kwargs)
def __init__(self, *args, **kwargs):
print "INIT BASE", args, kwargs
class foo(base, str):
def __new__(cls, *args, **kwargs):
return super(foo, cls).__new__(cls, *args, **kwargs)
def __init__(self, *args, **kwargs):
super(foo, self).__init__(*args, **kwargs)
这里foo('cat')
适用于:
>> NEW BASE: <class '__main__.foo'> ('cat',) {}
>> INIT BASE ('cat',) {}
但有一个论点foo('cat', x=3)
,它失败了:
>> NEW BASE: <class '__main__.foo'> ('cat',) {'x': 3}
Traceback (most recent call last):
File "inh.py", line 19, in <module>
foo('cat', x=3)
File "inh.py", line 12, in __new__
return super(foo, cls).__new__(cls, *args, **kwargs)
File "inh.py", line 4, in __new__
return super(base, cls).__new__(cls, *args, **kwargs)
TypeError: str() takes at most 1 argument (2 given)
我可以通过将base.__new__
方法更改为:
def __new__(cls, *args, **kwargs):
return super(base, cls).__new__(cls)
但现在我改变了调用结构,我觉得这会在以后给我带来问题。
如何正确地从字符串和第二类继承?