In the following snippet, I create a Counter object and I try add it to itself using three ways. Standard addition using '+', reducing from a list (internally does the same as previous) and using the function sum() from a list.
The first 2 work and return the expected result, but the third raises a TypeError exception.
From here I have two questions:
- What's the reason for the sum() failing if the addition works?
- When I add to objects with +, the __ add__ method of the class is used. What method, if any, is used when calling sum()?
Counter is only an example, I'm interested on the general case rather than this one in particular for when I create new classes.
from collections import Counter
from functools import reduce
a = Counter([1,1,1,1])
print(a+a+a)
print(reduce(lambda x, y: x + y, [a,a, a]))
sum([a, a, a])
prints:
Counter({1: 12})
Counter({1: 12})
Traceback (most recent call last):
File "/home/user/.PyCharmCE2019.3/config/scratches/scratch.py", line 20, in <module>
print(sum([a, a,]))
TypeError: unsupported operand type(s) for +: 'int' and 'Counter'
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…