Python中内置类的继承

问题描述 投票:0回答:1

即使代码中的第三行被注释,johny如何获得列表的功能,因为它是初始化?那么那条线的重要性是什么?

class Namedlist(list):
    def __init__(self,name):
          list.__init__([])  #This line even if commented does not affect the output
          self.name=name

johny=Namedlist(john)
johny.append("artist")
print(johny.name)
print(johny)

>>john
>>artist
python inheritance built-in
1个回答
1
投票

你的代码list.__init__([])中的行什么也没做,因为如果你想要修改你实例化的对象,你需要调用super()而不是内置的list(或者使用list.__init__(self, []),但这对我来说似乎更令人困惑)。

例如,调用super().__init__()对于传递列表的初始数据很有用。

我建议你改变你的代码:

class NamedList(list):
    def __init__(self, name, *args, **kwargs):
          # pass any other arguments to the parent '__init__()'
          super().__init__(*args, **kwargs)

          self.name = name

成为这样的用户:

>>> a = NamedList('Agnes', [2, 3, 4, 5])
>>> a.name
'Agnes'
>>> a
[2, 3, 4, 5]

>>> b = NamedList('Bob')
>>> b.name
'Bob'
>>> b
[]
>>> b.append('no')
>>> b.append('name')
>>> b
['no', 'name']

任何迭代都可以作为初始数据,而不仅仅是列表:

>>> c = NamedList('Carl', 'Carl')
>>> c.name
'Carl'
>>> c
['C', 'a', 'r', 'l']
© www.soinside.com 2019 - 2024. All rights reserved.