Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Anthony Grodowski
Anthony Grodowski
4,902 Points

How does sum(self) work?

I was wondering how is it possible that in @property 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?

1 Answer

Josh Keenan
Josh Keenan
20,315 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

Anthony Grodowski
Anthony Grodowski
4,902 Points

Thanks Josh for your answer but it's not excatly the case. I get that my class instance is a list and my class can use list methods because it inherits from that. The thing that concerns me is:

1 [<dice.D20 object at 0x7f1444cc0f98>, <dice.D20 object at 0x7f1444c20080>]     

2 9  

that's the output from this file and I don't get how python goes through these 2 objects in a list and takes from them D20().value