Say I have this class:
class MyString(str):
def someExtraMethod(self):
pass
I’d like to be able to do
a = MyString("Hello ")
b = MyString("World")
(a + b).someExtraMethod()
("a" + b).someExtraMethod()
(a + "b").someExtraMethod()
-
Running as is:
AttributeError: 'str' object has no attribute 'someExtraMethod' -
Obviously that doesn’t work. So I add this:
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 -
Hmmm, ok.
superdoesn’t appear to respect operator overloading. Perhaps: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__'
Still no luck. What should I be doing here?
I usually use the
super(MyClass, self).__method__(other)syntax, in your case this does not work becausestrdoes not provide__radd__. But you can convert the instance of your class into a string usingstr.To who said that its version 3 works: it does not:
And if you implement
__radd__you get anAttributeError(see the note below).Anyway, I’d avoid using built-ins as base type. As you can see some details may be tricky, and also you must redefine all the operations that they support, otherwise the object will become an instance of the built-in and not an instance of your class.
I think in most cases it’s easier to use delegation instead of inheritance.
Also, if you simply want to add a single method, then you may try to use a function on plain strings instead.
I add here a bit of explanation about why
strdoes not provide__radd__and what’s going on when python executes aBINARY_ADDopcode(the one that does the+).The abscence of
str.__radd__is due to the fact that string objects implements the concatenation operator of sequences and not the numeric addition operation. The same is true for the other sequences such aslistortuple. These are the same at “Python level” but actually have two different “slots” in the C structures.The numeric
+operator, which in python is defined by two different methods(__add__and__radd__) is actually a single C function that is called with swapped arguments to simulate a call to__radd__.Now, you could think that implementing only
MyString.__add__would fix your problem, sincestrdoes not implement__radd__, but that’s not true:As you can see
MyString.__add__is not called, but if we swap arguments:It is called, so what’s happening?
The answer is in the documentation which states that:
Which means you must implement all the methods of
strand the__r*__methods, otherwise you’ll still have problems with argument order.