6

我正在尝试创建一个继承自一个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)

但现在我改变了调用结构,我觉得这会在以后给我带来问题。

如何正确地从字符串和第二类继承

4

1 回答 1

3

你不能只做

def __new__(cls, *args, **kwargs):
    return super(base, cls).__new__(cls)

因为这将导致对 str 的new调用不正确(您不会传递允许的参数

>>> foo('t')
NEW  BASE: <class '__main__.foo'> ('t',) {}
INIT BASE ('t',) {}
''

你应该做类似的事情

def __new__(cls, *args, **kwargs):
    return super(base, cls).__new__(cls, *args[:1])

但是,如果您将base类用作类的混入,而该类的__new__方法接受多个参数,这可能会破坏某些东西。

作为一个选项,也许你应该继承类str但重写方法:

class CarelessStr(str):
    def __new__(cls, *args, **kwargs):
        return super(CarelessStr, cls).__new__(cls, *args[:1])

class foo(base, CarelessStr):
    def __new__(cls, *args, **kwargs):
        return super(foo, cls).__new__(cls, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        super(foo, self).__init__(*args, **kwargs)
于 2013-05-30T19:34:17.750 回答