-4

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?

apfel
  • 33
  • 6
  • 2
    Why would you want to override `__add__` for `int`? You'd break a whole truckload of things. – Colonel Thirty Two Feb 07 '15 at 16:43
  • 1
    yes thats what i want to do – apfel Feb 07 '15 at 16:44
  • Why do i get so many negative votes? I think the question is clear defined? – apfel Feb 07 '15 at 16:45
  • 3
    You cannot. You can create **new** types that alter behaviour by implementing the `__add__` method **on** that type, but you cannot alter existing built-in types. – Martijn Pieters Feb 07 '15 at 16:45
  • 3
    I don't see much research here. Did you find and read [Python: defining my own operators?](http://stackoverflow.com/q/932328) for example? Do you understand how Python uses special methods *on the type objects*? – Martijn Pieters Feb 07 '15 at 16:48

1 Answers1

2

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

See: http://code.activestate.com/recipes/384122/