说我有这门课:
class MyString(str):
def someExtraMethod(self):
pass
我希望能够做到
a = MyString("Hello ")
b = MyString("World")
(a + b).someExtraMethod()
("a" + b).someExtraMethod()
(a + "b").someExtraMethod()
按原样运行:
AttributeError: 'str' object has no attribute 'someExtraMethod'
显然那是行不通的。所以我添加了这个:
def __add__(self, other): return MyString(super(MyString, self) + other) def __radd__(self, other): return MyString(other + super(MyString, self))
TypeError: cannot concatenate 'str' and 'super' objects
嗯,好的。
super
似乎不尊重运算符重载。也许:def __add__(self, other): return MyString(super(MyString, self).__add__(other)) def __radd__(self, other): return MyString(super(MyString, self).__radd__(other))
AttributeError: 'super' object has no attribute '__radd__'
仍然没有运气。我应该在这里做什么?