Duane Smith1,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,
import random class Liar(list): def __init__(self, count, value): super().__init__() def __len__(self, count, value): return random.randint(value)
Julian Addison13,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
append. This helped me understand super a bit better. Your
Liar class can call the
super function to access the methods from its superclass
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.