在python上子类化列表 [英] Subclassing a list on python

查看:60
本文介绍了在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:
            raise ValueError("You must provide a die class")
        super().__init__()

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

基本上,它模拟一个具有多个骰子( size )和他们持有的骰子( die_class )的玩家.

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

我的困惑是为什么我们需要调用 super().__ init __ ?我尝试在没有它的情况下运行代码,并且效果很好!为什么需要打这个电话?

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?

推荐答案

如果基类要确保运行任何初始化代码,则需要调用 __ init __().没有呼叫就可以工作(似乎)是一个巧合,或者您可能还没有解决由此产生的问题.即使它在您当前使用的Python版本和实现中均能正常工作,也不能保证在不调用基类的 __ init __ 方法的情况下其他版本和实现也能正常工作.

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))

我已将 die_class 重命名为 die_factory ,因为可以在此处使用产生新die对象的任何可调用对象.

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

注意:这里可能违反 Hands list 之间的 is-a 关系,除非 Hands 对象实际上是一个 list ,即 all 的所有方法和列表的行为对于 Hands 对象也是有意义的.

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.

这篇关于在python上子类化列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆