为了账号安全,请及时绑定邮箱和手机立即绑定

在列表子类中,如何在创建实例时显式分配列表?

在列表子类中,如何在创建实例时显式分配列表?

繁星点点滴滴 2021-11-09 14:53:07
我有一个从列表继承的类。如何在创建实例时分配列表而不是在创建后附加到实例?示例代码:class ListObject(list):    def __init__(self, a, b, c):        self.a = a        self.b = b        self.c = cpremade_normal_list = [0, 1, 2, 3, 4, 5, 6]_list = ListObject(1, 2, 3) # Can I explicitly assign the premade list as this                             #  object while retaining attributes?# How I now have to do it.premade_normal_list = [0, 1, 2, 3, 4, 5, 6]_list = ListObject(1, 2, 3)for i in premade_normal_list:    _list.append(i)我试过了,这并不奇怪:class ListObject(list):    def __init__(self, a, b, c, _list):        self = _list        self.a = a        self.b = b        self.c = cpremade_normal_list = [0, 1, 2, 3, 4, 5, 6]_list = ListObject(1, 2, 3, premade_normal_list)我很难解释,希望它足够清楚......
查看完整描述

2 回答

?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

您需要调用父类的__init__.

def __init__(self, a, b, c, _list):    
    super().__init__(_list)
    self.a = a
    self.b = b
    self.c = c

但是,请注意,这对其他类ListObject将来可能继承的内容做出了某些假设。此定义不接受其他类可能需要的任何其他意外关键字参数。


查看完整回答
反对 回复 2021-11-09
?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

或者只是添加一个可选的 arg 到您的__init__():


class ListObject(list):

    def __init__(self, a, b, c, premade=None):

        self.a = a

        self.b = b

        self.c = c

        if premade is not None:

            self.extend(premade)


premade_normal_list = [0, 1, 2, 3, 4, 5, 6]

_list = ListObject(1, 2, 3, premade_normal_list)


查看完整回答
反对 回复 2021-11-09
  • 2 回答
  • 0 关注
  • 140 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号