[英]What is the difference between Python's __add__ and __concat__?
The list of Python's standard operators includes both __add__(a, b)
and __concat__(a, b)
. Python的标准运算符列表包括
__add__(a, b)
和__concat__(a, b)
。 Both of them are usually invoked by a + b
. 它们都通常由
a + b
调用。 My question is, what is the difference between them? 我的问题是,它们之间有什么区别? Is there a scenario where one would be used rather than the other?
是否存在使用一个而不是另一个的情况? Is there any reason you would define both on a single object?
你有什么理由在一个对象上定义它们吗?
Here's the documentation I found the methods mentioned in. 这是我找到的方法中提到的文档 。
Edit: Adding to the weirdness is this documentation : 编辑:添加到奇怪的是这个文档 :
Finally, sequence types should implement addition (meaning concatenation) and multiplication (meaning repetition) by defining the methods
__add__()
,__radd__()
,__iadd__()
,__mul__()
,__rmul__()
and__imul__()
described below;最后,序列类型应该通过定义下面描述的方法
__add__()
,__radd__()
__iadd__()
,__mul__()
__iadd__()
,__mul__()
__iadd__()
,__mul__()
__rmul__()
和__imul__()
来实现加法(意思是连接)和乘法(意思是重复); they should not define__coerce__()
or other numerical operators.他们不应该定义
__coerce__()
或其他数字运算符。
If you check the source for the operator
module ( add , concat ), you will find these definitions for those functions: 如果检查
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
So there is actually no difference except that concat
actually requires a sequence type. 所以实际上除了
concat
实际上需要序列类型之外没有区别。 Both functions use the +
operator which effect depends on the types you add. 这两个函数都使用
+
运算符,其效果取决于您添加的类型。
In general, using the operator
module is not that useful most of the time. 通常,在大多数情况下使用
operator
模块并不是那么有用。 The module is mostly used when you need to pass a function that performs an operation, for example to functional functions like map
, filter
, or reduce
. 当您需要传递执行操作的函数(例如
map
, filter
或reduce
等功能函数)时,主要使用该模块。 But usually, you can just use the +
operator directly. 但通常,您可以直接使用
+
运算符。
As for the underscore functions ( __add__
and __concat__
), these are just aliases : 至于下划线函数(
__add__
和__concat__
),这些只是别名 :
__add__ = add
__concat__ = concat
But those are of course not related to the special methods used to overload operators for custom types. 但这些当然与用于为自定义类型重载运算符的特殊方法无关。 They are functions that match the same name as those special methods, probably to make them appear similar.
它们是与那些特殊方法名称相同的函数,可能使它们看起来相似。 Note that there is no special
__concat__
method on objects though. 请注意,对象上没有特殊的
__concat__
方法。
Implementing __add__
on a custom type will however affect how the operator module functions work, for example: __add__
,在自定义类型上实现__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)
As you can see, operator.add
will use the implementation of the special method Example.__add__
; 如您所见,
operator.add
将使用特殊方法Example.__add__
;的实现。 but the reason for that is that the implementation of operator.add
just uses the +
operator (which behavior is explicitely defined by the special __add__
method). 但原因是
operator.add
的实现只使用了+
运算符(该行为由特殊的__add__
方法明确定义)。
operator.__add__(a, b)
: Return a + b
, for a
and b
numbers *. operator.__add__(a, b)
:返回a + b
,表示a
和b
数 *。 operator.__concat__(a, b)
: Return a + b
for a
and b
sequences . operator.__concat__(a, b)
:为a
和b
序列返回a + b
。 What's the difference? 有什么不同?
For example, you can't concatenate integers: 例如,您不能连接整数:
>>> operator.__concat__(2,3)
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'int' object can't be concatenated
__add__(a, b)
just does a + b
, hence it works on sequences too. __add__(a, b)
只做a + b
,因此它也适用于序列。 As per docs, 根据文档,
operator.__add__(a, b)
Return a + b, for a and b numbers.operator.__add__(a, b)
返回a + b,表示a和b数字。
operator.__concat__(a, b)
Return a + b for a and b sequences.operator.__concat__(a, b)
为a和b序列返回a + b。
operator.__add__(a, b): operator .__ add __(a,b):
It will just try to perform a + b
and give the result. 它只会尝试执行
a + b
并给出结果。
Eg. 例如。
operator.__add__(1,2) # performs 1 + 2
3
operator.__add__('a','b') # performs 'a'+'b'
'ab'
operator.__concat__(a, b): operator .__ concat __(a,b):
Here, it will check if a
has attribute __getitem__
. 在这里,它会检查,如果
a
有属性__getitem__
。 If it does not have __getitem__
attribute it raises an exception otherwise then try to perform a + b
. 如果它没有
__getitem__
属性,则会引发异常,否则尝试执行a + b
。
Eg. 例如。
On performing this operations on numbers, it will raise an exception. 在对数字执行此操作时,它将引发异常。
operator.__concat__(1,2)
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError:'int' object can't be concatenated
When performed on two strings, it perform string concatenation. 在两个字符串上执行时,它执行字符串连接。
operator.__concat__('a','b')
'ab'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.