gpt4 book ai didi

python - Python 的 __add__ 和 __concat__ 有什么区别?

转载 作者:太空狗 更新时间:2023-10-29 17:45:53 30 4
gpt4 key购买 nike

Python 的标准运算符列表包括 __add__(a, b)__concat__(a, b)。它们通常都由 a + b 调用。我的问题是,它们之间有什么区别?是否存在使用一种而不使用另一种的情况?您是否有任何理由在单个对象上定义两者?

这是 documentation我找到了中提到的方法。

编辑:更奇怪的是这个 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; they should not define __coerce__() or other numerical operators.

最佳答案

如果您检查 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

所以除了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__ 方法明确定义的).

关于python - Python 的 __add__ 和 __concat__ 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30924533/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com