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__
方法?還有其他方法可以做到這一點嗎?
您必須繼承'int()'。內置類型不是任意可擴展的。 –