Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override + operator in python for float + obj

Tags:

python

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.

like image 307
Arnab Datta Avatar asked Oct 14 '11 01:10

Arnab Datta


1 Answers

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.

like image 174
agf Avatar answered Sep 28 '22 08:09

agf