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

时间:2019-02-14 18:25:24

标签: 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 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)

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

2 个答案:

答案 0 :(得分:3)

您需要调用父类的MemTotal: 949448 kB MemFree: 33884 kB MemAvailable: 32544 kB Buffers: 796 kB Cached: 66032 kB SwapCached: 66608 kB Active: 483668 kB Inactive: 390360 kB Active(anon): 462456 kB Inactive(anon): 374188 kB Active(file): 21212 kB Inactive(file): 16172 kB Unevictable: 0 kB Mlocked: 0 kB SwapTotal: 102396 kB SwapFree: 3080 kB Dirty: 96 kB Writeback: 0 kB AnonPages: 740984 kB Mapped: 61176 kB Shmem: 29288 kB Slab: 21932 kB SReclaimable: 9084 kB SUnreclaim: 12848 kB KernelStack: 2064 kB PageTables: 7012 kB NFS_Unstable: 0 kB Bounce: 0 kB WritebackTmp: 0 kB CommitLimit: 577120 kB Committed_AS: 2873112 kB VmallocTotal: 1114112 kB VmallocUsed: 0 kB VmallocChunk: 0 kB CmaTotal: 8192 kB CmaFree: 6796 kB

__init__

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

答案 1 :(得分:2)

或仅向您的__init__()添加可选的arg:

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)