sum
is a built-in function in Python. __add__
is a special method. Every container object such as list has an __add__
method. You can see it in the guide. The __add__
methods in container objects and numeric objects work differently.
l = [1, 2, 3]
b = [4, 5, 6]
# Concatenation using .__add__()
print(l.__add__(b))
The result will be the concatenation of two lists,
[1, 2, 3, 4, 5, 6]
while the __add__
method in numeric objects will do the addition operation.
x = 2
y = 3
# addition operation: 2 + 3 = 5
print(x.__add__(y))
You can create a custom list with a sum
method.
class Custom(list):
# adding sum() functionallity
def sumup(self):
return sum(self)
Create new custom list object like this,
l = Custom([1, 2, 3])
and call the sumup method to sum all values inside the custom list
l.sumup()
+
/sum
.sum
does. It just iterates over the container and invokes__add__
, it doesn't have separate behaviour.sum
for it?