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

frustration.py

class Liar(list):

def doublelenght(self):
    return '{}{}'.format(self,self)

def __len__(self):
    return len(self.doublelenght())

bad_list = Liar([1,1])

print(bad_list) print(bad_list.doublelenght()) print(len(bad_list))

12

my idea was doubling the list and so the result I expected based on [1,1] was 4 but inseard instead is giving me 12, not sure the why this is happening.

frustration.py

Jura Streaming
Jura Streaming
8,082 Points

Hi! The len() is not 4 because it is counting characters inside string type of variable returned by doublelenght(), and there is 12 characters there

>>> print(bad_list.doublelenght())
[1, 1][1, 1]
>>> type(bad_list.doublelenght())
<type 'str'>
>>> len("[1, 1][1, 1]")
12
>>>

In your case, if I correctly understood what you drive to create, you need to expand list like so:

class Liar(list):
    def doublelenght(self):
        return self + self

    def __len__(self):
        return len(self.doublelenght())

and the test of it:

>>> bad_list = Liar([1,1])
>>> len(bad_list)
4
>>> bad_list.doublelenght()
[1, 1, 1, 1]
>>> len(bad_list.doublelenght())
4
>>>

2 Answers

So your method doubleleght[sic] is just printing out the list twice. So it's returning:

[1, 1][1, 1]

And your len method is just counting those characters. And as you can see, there are 12 characters so that's why you're getting 12. To get your intended result, try something like:

def doublelength(self):
    return len(self) * 2

That way you don't even need to bother overriding the len method.

got it thanks guys!!