I have two classes
Foo
Bar
class Foo(str):
def __add__(self, other):
return 'Foo.__add__ called'
class Bar(str):
def __radd__(self, other):
return 'Bar.__radd__ called'
Foo
__add__
Bar
__radd__
f = Foo('foo')
b = Bar('bar')
In [390]: f + b
Out[390]: 'Foo.__add__ called'
Bar.__radd__
Foo.__add__
There are two ways you can do this.
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'
Bar
a subclass of Foo
.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.