2013-01-06 16 views
0

我想重新定義__add__方法int使得使用情況會是這樣:如何重新定義'int'的__add__方法?

>> 1+2 
=> "1 plus 2" 

>> (1).__add__(2) 
=> "1 plus 2" 

我嘗試這樣做:

>>> int.__add__ = lambda self, x: str(self)+" plus " + str(x) 

然而,它拋出一個異常:

Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
TypeError: can't set attributes of built-in/extension type 'int' 

有沒有人有想法,爲什麼我不能重新定義這樣的__add__方法?還有其他方法可以做到這一點嗎?

+4

您必須繼承'int()'。內置類型不是任意可擴展的。 –

回答

3

創建您自己的類,它將覆蓋類的int類的方法。

In [126]: class myint(int): 
    def __add__(self,a): 
     print "{0} plus {1}".format(self,a) 
    .....:   

In [127]: a=myint(5) 

In [128]: b=myint(6) 

In [129]: a+b 
5 plus 6