我有一个从列表继承的类。如何在创建实例时分配列表而不是在创建后附加到实例?示例代码: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
将来可能继承的内容做出了某些假设。此定义不接受其他类可能需要的任何其他意外关键字参数。

明月笑刀无情
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)
添加回答
举报
0/150
提交
取消