Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Object-Oriented Python Advanced Objects Frustration

Chad Goldsworthy
Chad Goldsworthy
4,209 Points

Code passes challenge, but doesn't work in IDE

So for this quiz, I managed to pass with the following code:

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

However, when I save that code as a .py file on my computer and run it in terminal, and I do:

x = [1, 2, 3]
Liar(x)     # this returns [1, 2, 3] instead of the expected 8

It just returns the list to me, not the length? So the code it not actually working? Or am I missing something?

2 Answers

Steven Parker
Steven Parker
215,939 Points

A "Liar" object is an extension of a "list", so it most ways, a "Liar" will be the same as a list.

The difference is that if you get the length of a "Liar" object, it will give you the wrong result. Example:

tricky = Liar([1, 2, 3])
tricky        # this returns [1, 2, 3], as expected
len(tricky)   # this returns 8 instead of the expected 3!
Chad Goldsworthy
Chad Goldsworthy
4,209 Points

Okay I see. That makes complete sense, thanks so much

Dave StSomeWhere
Dave StSomeWhere
19,822 Points

Try print(len(Liar(x))) - you overrode the length method.