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 trialShawn Zhu
3,884 PointsGot stuck on a challenge task, please help.
Hey guys, can someone point out whats wrong with my code? Every time I press the recheck work button, it says:
TypeError: init() missing 1 required positional argument: 'alist'
I got frustrated so I copy and pasted my code into workspace, in the console I assigned a = [1, 2, 3, 4, 5] and put in len(Liar(a)), it will return 8 or 2 like the task asked me to do. But in the challenge window it alway shows an error, can anyone point out what`s wrong with my code or did I misunderstand the task? Thank you so much.
import random
class Liar(list):
def __init__(self, alist):
self.alist = alist
def __len__(self):
b = random.uniform(0, 4)
if b > 2:
return len(self.alist) + 3
elif b < 2:
return len(self.alist) - 3
1 Answer
Jeff Muday
Treehouse Moderator 28,722 PointsI like how you are approaching this challenge-- let's build on that.
There are so many ways that the challenge can be done correctly, but you're overthinking it somewhat. Because we are inheriting from list
most of the work has been done for us! (I like the sound of that)
We don't have to put in an __init__()
with a separate self.alist
since we are already have storage we inherited from the list()
class.
We only need to override the dunder len method __len()__
see below.
Good luck with Python, object orientation is something you will use all the time!
import random
class Liar(list):
def __len__(self):
# get length from superclass
super_len = super().__len__()
# liar_len can be any value that is not super_len
# your idea of using a random addition is perfect
liar_len = super_len + random.randint(1,4)
# finally return our liar_len
return liar_len
Shawn Zhu
3,884 PointsThank you for the help, good sir.
Shawn Zhu
3,884 PointsShawn Zhu
3,884 PointsHere is the task:
Now I want you to make a subclass of list. Name it Liar.
Override the len method so that it always returns the wrong number of items in the list. For example, if a list has 5 members, the Liar class might say it has 8 or 2.
You'll probably need super() for this.