operators - What is the difference between Python's __add__ and __concat__? -
the list of python's standard operators includes both __add__(a, b)
, __concat__(a, b)
. both of them invoked a + b
. question is, difference between them? there scenario 1 used rather other? there reason define both on single object?
here's documentation found methods mentioned in.
edit: adding weirdness documentation:
finally, sequence types should implement addition (meaning concatenation) , multiplication (meaning repetition) defining methods
__add__()
,__radd__()
,__iadd__()
,__mul__()
,__rmul__()
,__imul__()
described below; should not define__coerce__()
or other numerical operators.
if check source operator
module (add, concat), find these definitions functions:
def add(a, b): "same + b." return + b def concat(a, b): "same + b, , b sequences." if not hasattr(a, '__getitem__'): msg = "'%s' object can't concatenated" % type(a).__name__ raise typeerror(msg) return + b
so there no difference except concat
requires sequence type. both functions use +
operator effect depends on types add.
in general, using operator
module not useful of time. module used when need pass function performs operation, example functional functions map
, filter
, or reduce
. usually, can use +
operator directly.
as underscore functions (__add__
, __concat__
), these just aliases:
__add__ = add __concat__ = concat
but of course not related special methods used overload operators custom types. functions match same name special methods, make them appear similar. note there no special __concat__
method on objects though.
implementing __add__
on custom type affect how operator module functions work, example:
>>> 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) >>> = example(2) >>> b = example(4) >>> operator.add(a, b) example(6) >>> + b example(6)
as can see, operator.add
use implementation of special method example.__add__
; reason implementation of operator.add
uses +
operator (which behavior explicitely defined special __add__
method).
Comments
Post a Comment