Skip to content Skip to sidebar Skip to footer

Subclassing A List On Python

I am following a tutorial online and the code is this: class Hands(list): def __init__(self, size=0, die_class=None, *args, **kwargs): if not die_class: rai

Solution 1:

You need to call the __init__() if the base class to be sure any initialisation code there is run. That it (seems) to work without that call can be a coincidence, or you may simply haven't hit the resulting problem yet. Even if it works consistently in the Python version and implementation you are using currently, it isn't guaranteed for other versions and implementations to work without calling the base class' __init__ method.

Also you can actually use that call to populate the list with your dice objects:

classHands(list):
    def__init__(self, size=0, die_factory=None):
        ifnot die_factory:
            raise ValueError('You must provide a die factory')
        super().__init__(die_factory() for _ inrange(size))

I've renamed die_class to die_factory as any callable that produces a new die object can be used here.

Note: You may violate the is-a relationship between Hands and list here unless a Hands object actually is a list, i.e. all methods and behaviour of lists also make sense for Hands objects.

Solution 2:

super() lets you avoid referring to the base class explicitly. More importantly, with multiple inheritance, you can do stuff like this. At the end of the day, it is not necessary, it's just good practice.

Post a Comment for "Subclassing A List On Python"