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 trialUnashe Mutambashora
3,433 Pointscreating subclasses
how do I make Liar a subclass of list
class list:
def __init__(self,list = None,*args):
self.list = []
for arg in args:
self.list.append(arg)
def __len__(self):
return len(self.list)
class Liar(list):
def __len__(self):
super().__len__()
return len(self.list) + 2 or len(self.list) - 5
1 Answer
Megan Amendola
Treehouse TeacherHi, Unashe!
You don't need to create your own list class. List is a python object already, so you only need to create your Liar class and make list its parent. In order to make something a parent, you just pass it into your class. Like so:
class Liar(list):
pass
You have this already, which means the error is somewhere else in your code. For your method, when you call super.__len__()
you are actually already calling the len()
method. You're telling Python that when someone uses the len()
method on an instance of your Liar class, treat it the same way you treat calling len()
on a list. Your super.__len__()
then is the length.
def __len__(self):
length = super().__len__()
return length + 5
Unashe Mutambashora
3,433 PointsUnashe Mutambashora
3,433 PointsThanks Meg for the answer. Now I am confused. Why use len and super().len() when you get the same results if len() was used? Maybe they is something I am not understanding.
Megan Amendola
Treehouse TeacherMegan Amendola
Treehouse Teacher__len__()
islen()
. When you calllen()
on something ( likelen([1, 2, 3])
) Python looks for the dunder__len__
method on that object to see what to do. In my[1, 2, 3]
example, it checks that list's__len__
method and calls it.What you are doing is using super which brings Python up to the parent class (list) to call and use it's
__len__
method. So whenlen()
is used on an instance of class liar, likelen(Liar())
, it calls the__len__
you created which then calls the parent list's__len__
and gets the length of the object.So in the method, you can save the length result and add to it to create the "lie" length.