> The design pattern that has problems here is a bit unorthodox to start with.
I agree. This was meant strictly as a simple example for illustrative purposes. Steven D'Aprano's example from python-ideas may be a better one:
https://mail.python.org/pipermail/python-ideas/2017-April/045455.html
class A:
def __add__(self, other):
self.log()
...
__radd__ = __add__
class B(A):
def log(self):
...
Our actual use case for NumPy involved writing a mixin that look more like this, that expects a specified method to implement arithmetic, i.e.,
class NDArrayOperatorsMixin:
def __add__(self, other):
return self._calculate(np.add, self, other)
def __radd__(self, other):
return self._calculate(np.add, other, self)
... # repeat for all special methods
class A(NDArrayOperatorsMixin):
def _calculate(self, op, *args):
if not all(isinstance(arg, A) for arg in args):
return NotImplemented
... # implement calculation
class B(A):
def _calculate(self, op, *args):
... # something different
In A() + B(), B never gets the chance to override A's implementation of __add__ via _calculate, because it overrode a different method (_calculate) which happens to contain the *implementation* for __radd__, but not __radd__ itself.
Anyways, if you have serious concerns about changing this, it is probably best respond to Guido on python-ideas:
https://mail.python.org/pipermail/python-ideas/2017-April/045468.html |