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 Object-Oriented Python Advanced Objects Frustration

Simon Amz
Simon Amz
4,606 Points

Confusion between using __len__ overrided or not

I my code below, the length output is always 5, even with the modification the de return 'count = len(self) + 3'

How to modify the value of an attribute in a magic function?

Thanks for your help

frustration.py
class Liar(list):

    def __len__(self, length):
        count = super().__len__(self)
        count = len(self) + 3
        return count

# test = Liar()
# test = [1, 3, 33, 'hello', "dog"]
# print(test.__len__())

1 Answer

Sebastian Popa
Sebastian Popa
11,094 Points

First of all , for __len__ you need only 1 argument and that is self. Maybe try this :

class Liar(list):
    def __len__(self):
        return super().__len__() + 2

[MOD: added backtick formatting -cf]

Chris Freeman
Chris Freeman
Treehouse Moderator 68,441 Points

Also, calling len() from within the __len__ method causes infinite recursion:

RecursionError: maximum recursion depth exceeded