11

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.

3
  • I didn't see the "Something general will be more useful than a specific implementation as I need to implement the same thing for multiplication, subtraction etc." part but the link in my answer will take you to the list of magic methods used to emulate a numeric type.
    – agf
    Oct 14, 2011 at 1:29
  • 1
    It's okay, I stopped reading after "You're looking for radd" and clicked on the link :) However, your code did make it a lot clearer, so thanks Oct 14, 2011 at 1:33
  • If you have a custom __add__() for your class, then right after its definition you could just include a line __radd__ = __add__. This works because radd swaps the argument order for you.
    – Bob Stein
    Jun 1, 2015 at 13:09

3 Answers 3

11

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.

3

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

1
  • If you look at his question and the code he linked he's already using __add__.
    – agf
    Oct 14, 2011 at 1:14
3

implement __radd__ . When you call 3.3 + Vec3D(1,0,0), as long as float doesn't have method __add__(y) with y being Vec3D, your reflected version __radd__ will be called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.