python - Changing the order of operation for __add__, __mul__, etc. methods in a custom class -


i have vector class:

class vector:     def __init__(self, x, y):         self.x, self.y = x, y     def __str__(self):         return '(%s,%s)' % (self.x, self.y)     def __add__(self, n):         if isinstance(n, (int, long, float)):             return vector(self.x+n, self.y+n)         elif isinstance(n, vector):             return vector(self.x+n.x, self.y+n.y) 

which works fine, i.e. can write:

a = vector(1,2) print(a + 1) # prints (2,3) 

however if order of operation reversed, fails:

a = vector(1,2) print(1 + a) # raises typeerror: unsupported operand type(s)              #                   +: 'int' , 'instance' 

i understand error: addition of int object vector object undefined because haven't defined in int class. there way work around without defining in int (or parent of int) class?

you need define __radd__

some operations not evaluate + b == b + , that's why python defines add , radd methods.

explaining myself better: supports fact "int" not define + operation class vector instances part of operation. therefore vector + 1 not same 1 + vector.

when python tries see 1.__add__ method can do, exception raised. , python goes , looks vector.__radd__ operation try complete it.

in op's case evaluation true , suffices __radd__ = __add__

class vector(object):      def __init__(self, x, y):         self.x, self.y = x, y      def __str__(self):         return '(%s,%s)' % (self.x, self.y)      def __add__(self, n):         if isinstance(n, (int, long, float)):             return vector(self.x+n, self.y+n)         elif isinstance(n, vector):             return vector(self.x+n.x, self.y+n.y)      __radd__ = __add__   = vector(1, 2) print(1 + a) 

which outputs:

(2,3) 

the same applies number-like operations.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -