How can i override the "+" Operator in Python 2.7?
import operator
def __add__(a,b)
return a + b + 5
print 5 + 4
This does not work, how can override it?
How can i override the "+" Operator in Python 2.7?
import operator
def __add__(a,b)
return a + b + 5
print 5 + 4
This does not work, how can override it?
You could do something like this... however, this will only modify +
for instances of MyIntType
.
>>> import types
>>> class MyIntType(types.IntType):
... def __add__(self, other):
... return other + 5 + int(self)
...
>>> i = MyIntType()
>>> i + 2
7
If you want to "override" __add__
, you should pick what types of instances you want to "override" it for. Otherwise, you might be able to muck with python's parser... but I wouldn't go there.
There's alternately the hack to create your own operators. While this is not exactly what you are asking for, it might be more of what you want if you don't want to modify the __add__
behavior for a single type as I did above.
>>> class Infix:
... def __init__(self, function):
... self.function = function
... def __ror__(self, other):
... return Infix(lambda x, self=self, other=other: self.function(other, x))
... def __or__(self, other):
... return self.function(other)
... def __rlshift__(self, other):
... return Infix(lambda x, self=self, other=other: self.function(other, x))
... def __rshift__(self, other):
... return self.function(other)
... def __call__(self, value1, value2):
... return self.function(value1, value2)
...
>>> pls = Infix(lambda x,y: x+y+5)
>>> 0 |pls| 2
7