Python Object-Oriented Python Advanced Objects Frustration

Duane Smith
Duane Smith
1,673 Points

I'm trying to create a class where I return a random value when I call the __len__ method in a new class called Liar.

I'm making Liar a subclass of List and I'm working through the problem the best I can. However, I've ran into an issue and I've tried a ton of variations over the last few days and it seems I'm just not approaching this issue from the right direction even remotely. A nudge would be very much appreciated from anyone!

Thank you and best regards,

Duane

frustration.py
import random
class Liar(list):
    def __init__(self, count, value):
        super().__init__()

    def __len__(self, count, value):
        return random.randint(value)
Duane Smith
Duane Smith
1,673 Points

Julian Addison

Thanks a ton man! You really took time to explain things and you gave me a new resource to check out as well. I'll crack this challenge with no problem. Thanks a ton for the assistance!

Duane Smith

1 Answer

Julian Addison
Julian Addison
13,298 Points

You don't even have to include the __init__ method here. Your class could be empty:

class Liar(list):
    pass

and it would still inherit methods like __len__ or append. This helped me understand super a bit better. Your Liar class can call the super function to access the methods from its superclass list

It would help if your new __len__ method were to actually use the __len__ method it inherits from the class list. That way, you can ensure that the result is always different from the class instance's actual length.

class Liar(list):
    def super_append(self, addition):
        return super().append('super ' + addition)

I hope this example gives you a better idea of how to incorporate super into your subclasses.