Python Object-Oriented Python Advanced Objects Frustration

Unashe Mutambashora
Unashe Mutambashora
2,483 Points

creating subclasses

how do I make Liar a subclass of list

frustration.py
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
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree seal-36
Megan Amendola
Treehouse Teacher

Hi, 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
Unashe Mutambashora
2,483 Points

Thanks 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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Megan Amendola
Treehouse Teacher

__len__() is len(). When you call len() on something ( like len([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 when len() is used on an instance of class liar, like len(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.

class Liar(list):
    def __len__(self):
        length = super().__len__()
        return length + 5