Anthony Grodowski4,902 Points
How does sum(self) work?
I was wondering how is it possible that in
from dice import D20 class Hand(list): def __init__(self, list_sum=None): self.list_sum = list_sum @classmethod def roll(cls, times): list_sum = cls() for _ in range(times): list_sum.append(D20()) return list_sum @property def total(self): return sum(self) a= Hand.roll(2) print(1, a) print(2, a.total)
returns summed value of two
D20.value(), even tho we provided only
D20(). How does python know that by saying
return sum(self) we want to recieve value attributes?
Josh Keenan19,297 Points
Hand is inheriting from list, you can call the sum operation on a list as
sum() takes an iterable, your hand class inherits from list meaning sum will treat it the same way it would a list