如何为`int`重新定义`__add__`方法?

时间:2013-01-06 15:28:10

标签: python operators

我想为__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__方法的想法有所了解?还有其他方法吗?

2 个答案:

答案 0 :(得分:3)

创建自己的类,该类覆盖__add__类的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

答案 1 :(得分:0)

尽管不是最佳实践,但是您可以使用forbiddenfruit覆盖__add__方法。用法:

>>> from forbiddenfruit import curse
>>> curse(int, '__add__', lambda x, y: f"{x} plus {y}")
>>> 1 + 2
'1 plus 2'