0

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?

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

1 Answers1

1

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).

The call to super().__init__() is usefull to pass along initial data for the list, for example.

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']
Ralf
  • 16,086
  • 4
  • 44
  • 68
  • But even without using super or list.__init__ the johny object gets functionality of list.How is that? – Vedant Bhosale Feb 27 '19 at 14:26
  • @VedantBhosale Because it inherits from `list` (the class definition is `class NamedList(list):`). The call to `__init__()` is only object initialization; the methods on the object (for example `.append()`) exist regardless of the call to `super.__init__()` in the `NamedList.__init__()` method. – Ralf Feb 27 '19 at 15:10
  • Initialization is done to inherit different attributes which are already defined in base class but here base class is a list so why is initialization done in this code? – Vedant Bhosale Mar 02 '19 at 14:15
  • @VedantBhosale in [this question](https://stackoverflow.com/q/46324470/9225671) there are a few explanations of why you should call the superclass' `__init__()` even though the call is not strictly necessary – Ralf Mar 02 '19 at 16:13