Python Object-Oriented Python Advanced Objects Frustration

Chad Goldsworthy
Chad Goldsworthy
4,207 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
167,904 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,207 Points

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

Dave StSomeWhere
Dave StSomeWhere
19,768 Points

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