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 56,648 Points

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

RecursionError: maximum recursion depth exceeded