I have a class that is basically an optimised generator (like range
). It implements __getitem__
, __iter__
and __contains__
. It also needs to implement addition of its items (immutable numbers) with that of another instance:
def addition(self, other):
for x in zip(self, other):
yield sum(x)
and concatenation of two instances:
def concatenation(self, other):
yield from self
yield from other
(The real methods return instances of subclasses that implement this in their __iter__
method, with necessary optimisations to reduce the complexity of __contains__
where possible, but I simplified it for the example.)
Types such as str
, list
and tuple
implement concatenation with __add__
. Types such as int
and float
implement addition with __add__
. I can't implement both with __add__
.
What magic methods should I use for addition and concatenation if a class implements both?