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

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
231,248 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,870 Points

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