I have a class Vec3D (see http://pastebin.com/9Y7YbCZq)
Currently, I allow Vec3D(1,0,0) + 1.2 but I'm wondering how I should proceed to overload the + operator in such a way that I get the following output:
>>> 3.3 + Vec3D(1,0,0)
[4.3, 3.3 , 3.3]
Code is not required, but just a hint in which direction I should look. Something general will be more useful than a specific implementation as I need to implement the same thing for multiplication, subtraction etc.
You're looking for __radd__
:
class MyClass(object):
def __init__(self, value):
self.value = value
def __radd__(self, other):
print other, "radd", self.value
return self.value + other
my = MyClass(1)
print 1 + my
# 1 radd 1
# 2
If the object on the left of the addition doesn't support adding the object on the right, the object on the right is checked for the __radd__
magic method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With