如果你检查的operator
模块(add,concat)源代码,你会发现这些函数的定义:
def add(a, b):
"Same as a + b."
return a + b
def concat(a, b):
"Same as a + b, for a and b sequences."
if not hasattr(a, '__getitem__'):
msg = "'%s' object can't be concatenated" % type(a).__name__
raise TypeError(msg)
return a + b
因此,实际上有不同之处在于concat
没有区别实际上需要一个序列类型。这两个函数都使用+
运算符,其效果取决于您添加的类型。
一般来说,在大多数情况下使用operator
module并不是那么有用。当您需要将执行操作的功能(例如,功能功能如map
,filter
或reduce
)传递给模块时,通常会使用该模块。但通常,您可以直接使用+
运算符。
至于下划线函数(__add__
和__concat__
),这些是just aliases:
__add__ = add
__concat__ = concat
但这些当然不相关的用于重载操作自定义类型的special methods。它们是与这些特殊方法相同名称的函数,可能会使它们显得相似。请注意,对象上没有特殊的__concat__
方法。
上的自定义类型实现__add__
但将影响到运营商模块功能的工作,例如:
>>> class Example:
def __init__ (self, x):
self.x = x
def __repr__ (self):
return 'Example({})'.format(self.x)
def __add__ (self, other):
return Example(self.x + other.x)
>>> a = Example(2)
>>> b = Example(4)
>>> operator.add(a, b)
Example(6)
>>> a + b
Example(6)
正如你所看到的,operator.add
将使用特殊的方法Example.__add__
的执行情况;但其原因在于operator.add
的实现仅使用+
运算符(该行为由特殊的__add__
方法明确定义)。
那么根据您链接到一个文档是数字和一个用于序列 – Craicerjack
注意'__concat__'不是*“魔术方法” *像'__add__'是:https://开头的文档.python.org/2/reference/datamodel.html – jonrsharpe
*是否有区别,名称除外? – user2864740