在Python中有什么方法可以在Python中获取整数的加法对象(运算符+)并将其存储在某个地方吗?
请您参考如下方法:
>>> int_add = int.__add__
>>> int_add(1, 2)
3
您还可以使用 operator.add获取用于在 Python 中添加的通用函数:
>>> from operator import add
>>> add(1, 2)
3
>>> add('a', 'b')
'ab'
如果想获取特定整数的加法方法,而不是int类型,请看gnibbler对问题的评论:
To get the bound add method of an integer you should use parentheses to prevent the . being treated as a decimal point. eg
(1).__add__. Another way would be to add a space between the1and the.eg1 .__add__but I think that it is too obscure.
一个例子:
>>> one_add = 1 .__add__
>>> one_add(2)
3
