如果你檢查的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