猿问

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

我有一个从列表继承的类。如何在创建实例时分配列表而不是在创建后附加到实例?示例代码:


class ListObject(list):

    def __init__(self, a, b, c):

        self.a = a

        self.b = b

        self.c = c



premade_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 = c


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

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

我很难解释,希望它足够清楚......


繁星点点滴滴
浏览 141回答 2
2回答

拉风的咖菲猫

您需要调用父类的__init__.def __init__(self, a, b, c, _list):         super().__init__(_list)     self.a = a     self.b = b     self.c = c但是,请注意,这对其他类ListObject将来可能继承的内容做出了某些假设。此定义不接受其他类可能需要的任何其他意外关键字参数。

明月笑刀无情

或者只是添加一个可选的 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)
随时随地看视频慕课网APP

相关分类

Python
我要回答