简体   繁体   English

Python的__add__和__concat__有什么区别?

[英]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模块的源( addconcat ),您将找到这些函数的这些定义:

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 . 当您需要传递执行操作的函数(例如mapfilterreduce等功能函数)时,主要使用该模块。 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 ,表示ab *。
  • operator.__concat__(a, b) : Return a + b for a and b sequences . operator.__concat__(a, b) :为ab 序列返回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

  • actually __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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM