2015-02-07 107 views
-5

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

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

print 5 + 4 

这是行不通的,怎么能覆盖它呢?

+1

你为什么要重写''为int' __add__'?你会打破一大堆的东西。 – 2015-02-07 16:43:09

+0

是的,这就是我想要做的 – apfel 2015-02-07 16:44:46

+0

为什么我得到这么多的负面投票?我认为这个问题是明确的定义? – apfel 2015-02-07 16:45:43

回答

1

你可以这样做......但是,这只会修改+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/