I recently learned about operator overloading in python and I would like to know if the following is possible.
Consider the folowing hypothetica/contrived class.
class My_Num(object):
def __init__(self, val):
self.val = val
def __add__(self, other_num):
if isinstance(other_num, My_Num):
return self.val + other_num.val
else:
return self.val + other_num
I know that the way that's written above, I can do things like this
n1 = My_Num(1)
n2 = My_Num(2)
n3 = 3
print n1 + n2
print n1 + n3
and those will work as expected. I also know that the way it's currently written I can't do this
n1 = My_Num(1)
n2 = 2
print 2 + n1
Is there anyway around this? I know this example is contrived but I have an application in which it would ve very useful if when I did operator overloading, the class for which I define the operator can appear on the right hand side of operator. Is this possible in python?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…