繁星點(diǎn)點(diǎn)滴滴
2021-11-09 14:53:07
我有一個(gè)從列表繼承的類。如何在創(chuàng)建實(shí)例時(shí)分配列表而不是在創(chuàng)建后附加到實(shí)例?示例代碼: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 回答

拉風(fēng)的咖菲貓
TA貢獻(xiàn)1995條經(jīng)驗(yàn) 獲得超2個(gè)贊
您需要調(diào)用父類的__init__
.
def __init__(self, a, b, c, _list): super().__init__(_list) self.a = a self.b = b self.c = c
但是,請(qǐng)注意,這對(duì)其他類ListObject
將來可能繼承的內(nèi)容做出了某些假設(shè)。此定義不接受其他類可能需要的任何其他意外關(guān)鍵字參數(shù)。

明月笑刀無情
TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超4個(gè)贊
或者只是添加一個(gè)可選的 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)
添加回答
舉報(bào)
0/150
提交
取消