简体   繁体   中英

How can I delegate to the __add__ method of a superclass?

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()
  1. Running as is:

     AttributeError: 'str' object has no attribute 'someExtraMethod' 
  2. 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 
  3. Hmmm, ok. super doesn'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 because str does not provide __radd__ . But you can convert the instance of your class into a string using str .

To who said that its version 3 works: it does not:

>>> class MyString(str):
...     def __add__(self, other):
...             print 'called'
...             return MyString(super(MyString, self).__add__(other))
... 
>>> 'test' + MyString('test')
'testtest'
>>> ('test' + MyString('test')).__class__
<type 'str'>

And if you implement __radd__ you get an AttributeError (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 str does not provide __radd__ and what's going on when python executes a BINARY_ADD opcode(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 as list or tuple . 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, since str does not implement __radd__ , but that's not true:

>>> class MyString(str):
...     def __add__(self, s):
...             print '__add__'
...             return MyString(str(self) + s)
... 
>>> 'test' + MyString('test')
'testtest'

As you can see MyString.__add__ is not called, but if we swap arguments:

>>> MyString('test') + 'test'
__add__
'testtest'

It is called, so what's happening?

The answer is in the documentation which states that:

For objects x and y , first x.__op__(y) is tried. If this is not implemented or returns NotImplemented , y.__rop__(x) is tried. If this is also not implemented or returns NotImplemented , a TypeError exception is raised. But see the following exception:

Exception to the previous item: if the left operand is an instance of a built-in type or a new-style class, and the right operand is an instance of a proper subclass of that type or class and overrides the base's __rop__() method, the right operand's __rop__() method is tried before the left operand's __op__() method.

This is done so that a subclass can completely override binary operators. Otherwise, the left operand's __op__() method would always accept the right operand: when an instance of a given class is expected, an instance of a subclass of that class is always acceptable.

Which means you must implement all the methods of str and the __r*__ methods, otherwise you'll still have problems with argument order.

May be:

class MyString(str):
  def m(self):
    print(self)

  def __add__(self, other):
    return MyString(str(self) + other)

  def __radd__(self, other):
    return MyString(other + str(self))    

a = MyString("Hello ")
b = MyString("World")
(a + b).m()

Update: you last version with super works for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM