If a class implements addition and concatenation, which magic methods should be used for what?

时间:2017-08-05 10:43:02

标签: python python-3.x magic-methods

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?

0 个答案:

没有答案