简体   繁体   English

从Python中的buitin类继承

[英]Inheritence from buitin class in Python

How does johny gets the functionality of list even if the third line in the code is commented, as it is the initialisation?So then what is the significance of that line? 即使代码中的第三行被注释了,约翰尼又如何获得list的功能(因为它是初始化的),那么那行的意义是什么?

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

The line in your code list.__init__([]) does nothing because you if you want to modify the object you are instantiating, you need to call super() not the list built-in (or use list.__init__(self, []) , but that seems more confusing to me). 代码list.__init__([])的行list.__init__([])无效,因为如果您要修改实例化的对象,则需要调用super()而不是内置list (或使用list.__init__(self, []) ,但对我来说似乎更令人困惑)。

The call to super().__init__() is usefull to pass along initial data for the list, for example. 例如,对super().__init__()的调用可用于传递列表的初始数据。

I suggest you change your code to this: 我建议您将代码更改为此:

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

          self.name = name

To be user like this: 成为这样的用户:

>>> 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']

Any iterable works as initial data, not just lists: 任何可迭代的内容都可以用作初始数据,而不仅仅是列表:

>>> c = NamedList('Carl', 'Carl')
>>> c.name
'Carl'
>>> c
['C', 'a', 'r', 'l']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM