cᴏʟᴅsᴘᴇᴇᴅ cᴏʟᴅsᴘᴇᴇᴅ - 3 years ago 92
Python Question

Suppressing __add__ when __radd__ is defined

I have two classes

Foo
and
Bar
:

class Foo(str):
def __add__(self, other):
return 'Foo.__add__ called'


class Bar(str):
def __radd__(self, other):
return 'Bar.__radd__ called'


As you can see, I have
Foo
implementing
__add__
and
Bar
implementing
__radd__
.

I can create objects of these classes and add them, because the magic methods are defined.

f = Foo('foo')
b = Bar('bar')


However, adding them produces this:

In [390]: f + b
Out[390]: 'Foo.__add__ called'


How can I set it so that
Bar.__radd__
method is called in preference to
Foo.__add__
?

Answer Source

There are two ways you can do this.

  1. Add an explicit check in Foo related to Bar.

class Foo(str):
    def __add__(self, other):
        if isinstance(other, Bar):
            return NotImplemented
        return 'Foo.__add__ called'


class Bar(str):
    def __radd__(self, other):
        return 'Bar.__radd__ called'
  1. Make Bar a subclass of Foo.

From docs:

Note: If the right operand’s type is a subclass of the left operand’s type and that subclass provides the reflected method for the operation, this method will be called before the left operand’s non-reflected method. This behavior allows subclasses to override their ancestors’ operations.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download