2015-02-07 104 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/