Python覆盖+Op

2024-05-03 11:29:51 发布

您现在位置:Python中文网/ 问答频道 /正文

如何重写Python2.7中的“+”运算符?

import operator
def __add__(a,b)
    return a + b + 5

print 5 + 4

这不起作用,怎么能覆盖它?在


Tags: importaddreturndef运算符operatorprint
1条回答
网友
1楼 · 发布于 2024-05-03 11:29:51

你可以这样做。。。但是,这只会修改+的实例MyIntType。在

>>> import types
>>> class MyIntType(types.IntType):
...   def __add__(self, other):
...     return other + 5 + int(self)        
... 
>>> i = MyIntType()
>>> i + 2
7

如果你想“重写”__add__,你应该选择你想要“重写”它的实例类型。否则,您可能可以处理python的解析器。。。但我不会去那里。在

有交替的黑客创建自己的运营商。虽然这并不是您所要求的,但是如果您不想像我上面所做的那样修改单个类型的__add__行为,那么它可能更符合您的需要。在

^{pr2}$

参见:http://code.activestate.com/recipes/384122/

相关问题 更多 >