使用法が次のようになるように、__add__
メソッドを再定義したいと思います。int
>> 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__
このような方法を再定義できないのかについて誰かが考えを持っていますか?そして、これを行う他の方法はありますか?