Subclassing a list on python

微笑、不失礼 提交于 2019-12-23 21:36:42

问题


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:
            raise ValueError("You must provide a die class")
        super().__init__()

        for _ in range(size):
            self.append(die_class())

It basically models a player with a number of dice (size) and what dice they are holding (die_class).

My confusion is why do we need to call super().__init__? I tried running the code without it and it worked fine! Why is the call necessary?


回答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:

class Hands(list):
    def __init__(self, size=0, die_factory=None):
        if not die_factory:
            raise ValueError('You must provide a die factory')
        super().__init__(die_factory() for _ in range(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.




回答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.



来源:https://stackoverflow.com/questions/46324470/subclassing-a-list-on-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!