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