Python的标准运算符列表包括__add__(a, b)和__concat__(a, b).它们通常都被调用a + b.我的问题是,它们之间有什么区别?是否存在使用一个而不是另一个的情况?你有什么理由在一个对象上定义它们吗?
这是我找到的方法中提到的文档.
编辑:添加到奇怪的是这个文档:
最后,序列类型应该实现加成(意味着串联)和乘法(意味着重复)通过定义的方法
__add__(),__radd__(),__iadd__(),__mul__(),__rmul__()和__imul__()下面描述的; 他们不应该定义__coerce__()或其他数字运算符.
pok*_*oke 11
如果检查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
Run Code Online (Sandbox Code Playgroud)
所以实际上除了concat实际需要序列类型之外没有区别.这两个函数都使用+运算符,其效果取决于您添加的类型.
通常,在大多数情况下使用该operator模块并不是那么有用.该模块主要用于当需要传递执行的操作的功能,例如功能性的功能,如map,filter,或reduce.但通常,您可以直接使用+运算符.
至于下划线函数(__add__和__concat__),这些只是别名:
__add__ = add
__concat__ = concat
Run Code Online (Sandbox Code Playgroud)
但这些当然与用于为自定义类型重载运算符的特殊方法无关.它们是与那些特殊方法名称相同的函数,可能使它们看起来相似.请注意,__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)
Run Code Online (Sandbox Code Playgroud)
如您所见,operator.add将使用特殊方法的实现Example.__add__; 但原因是operator.add只使用+运算符的实现(这种行为是由特殊__add__方法明确定义的).