Python Commutative Operator Override
Hi I was wondering if there is a way to do a symmetric operator override in Python. For example, let's say I have a class: class A: def __init__(self, value): self.valu
Solution 1:
Just implement an __radd__
method in your class. Once the int class can't handle the addition, the __radd__
if implemented, takes it up.
classA(object):
def__init__(self, value):
self.value = value
def__add__(self, other):
ifisinstance(other, self.__class__):
return self.value + other.value
else:
return self.value + other
def__radd__(self, other):
return self.__add__(other)
a = A(1)
print a + 1# 2print1 + a
# 2
For instance, to evaluate the expression x - y, where y is an instance of a class that has an
__rsub__()
method,y.__rsub__(x)
is called ifx.__sub__(y)
returnsNotImplemented
.
Same applies to x + y
.
On a side note, you probably want your class to subclass object
. See What is the purpose of subclassing the class "object" in Python?
Post a Comment for "Python Commutative Operator Override"