In my classes, I often use overloading like in this site to define their behavior when using operators like +
,-
, etc. by overwriting the __add__
,__sub__
, etc. methods.
An example would be this:
class MyClass:
def __add__(self, other):
result = my_custom_adder(self, other)
return self.__class__(result)
Is there any way to define the behavior when chaining of such overwritten operators?
For example, an addition of three elements a + b + c
of a complex class could be implemented much more efficiently by taking all three elements into account at once and not just calculating (a + b) + c
sequentially.
Of cause I can just introduce a classmethod:
class MyClass:
def __add__(self, other):
return self.my_custom_adder(self, other)
@classmethod
def my_custom_adder(cls, *args):
result = do_efficient_addition(*args)
return cls(result)
Then, I can call my_custom_adder(a, b, c)
instead. But this requires the user to know that there is a method like this and calling it explicitly, instead of just using a + b + c
.