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

Python 在列表子类中,如何在创建实例时显式分配列表?,python,python-3.x,class,inheritance,Python,Python 3.x,Class,Inheritance,我有一个从列表继承的类。如何在创建实例时分配列表,而不是在创建后附加到实例? 示例代码: 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 explicitl

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

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)

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

您需要调用父类的
\uuuu init\uuu

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

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

您需要调用父类的
\uuuuu init\uuuu

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

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

或者只需向
\uuuu init\uuuu()添加可选参数即可。


或者只需将可选参数添加到
\uuu init\uuu()


可能也有理由覆盖
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu>但我没有想到。你会知道哪个解决方案更快吗?我不知道。