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