Python Override + Operator

时间:2015-02-07 16:40:50

标签: python python-2.7

如何覆盖Python 2.7中的“+”运算符?

import operator
def __add__(a,b)
    return a + b + 5

print 5 + 4

这不起作用,如何覆盖呢?

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作...但是,这只会针对+的实例修改MyIntType

>>> import types
>>> class MyIntType(types.IntType):
...   def __add__(self, other):
...     return other + 5 + int(self)        
... 
>>> i = MyIntType()
>>> i + 2
7

如果你想“覆盖”__add__,你应该选择你想要“覆盖”它的实例类型。否则,你可能会用python的解析器捣乱......但我不会去那里。

另外还有黑客来创建自己的运营商。虽然这不是您要求的,但如果您不想像我上面那样修改单个类型的__add__行为,那么它可能更符合您的要求。

>>> 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

请参阅:http://code.activestate.com/recipes/384122/