Override + operator in python for float + obj

I have a Vec3D class (see http://pastebin.com/9Y7YbCZq )

I currently enable Vec3D (1,0,0) + 1,2, but I wonder how I should overload the + operator in such a way as to get the following result:

>>> 3.3 + Vec3D(1,0,0) [4.3, 3.3 , 3.3] 

No code is required, but just a hint in which direction I should look. Something in common will be more useful than a specific implementation, since I need to implement the same thing for multiplication, subtraction, etc.

+8
python
source share
3 answers

You are 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 to the left of the addition does not support adding the object to the right, the object to the right is checked for the magic method __radd__ .

+10
source share

You want to use the __add__ methods (and possibly __radd__ and __iadd__ ). See http://docs.python.org/reference/datamodel.html#object.__add__ for more details.

+3
source share

implement __radd__ . When you call 3.3 + Vec3D(1,0,0) until the float has the __add__(y) method, when y is Vec3D, your displayed version is __radd__ .

+3
source share

All Articles