(Feb-19-2019, 10:18 AM)AlekseyPython Wrote: How I can use the familiar square bracket operator?
square bracket
[]
or
list()
are not an operator(as in C++) in Python,it's a built-in Immutable datatype.
Quote:I created my own class- collection and I don’t want to write the add method everywhere
You can just write
add()
method once,then can all sub-class inherit from it using
super()
.
class Foo:
def __init__(self):
self.my_lst = []
def add(self, item):
self.my_lst.append(item)
class Bar(Foo):
def __init__(self):
super().__init__()
Use:
>>> o = Bar()
>>> o.add('hello')
>>> o.add(9999)
>>> o.my_lst
['hello', 9999]
>>> o.my_lst.pop()
9999
>>> o.my_lst
['hello']
If want to be cool

and have all list method on object.
List type does the actual initialisation of the list inside it's
__init__()
method.
Only need to overwrite
__new__()
when subtyping immutable types.
class MyList(list):
def __init__(self, name, *args):
super().__init__(self, *args)
self.name = name
Use:
>>> o = MyList('my_list')
>>> o.append('Car')
>>> o.append(7777)
>>> o
['Car', 7777]
>>> o.index('Car')
0
>>> o.name
'my_list'
# All list method are on object,together with <name>
>>> [i for i in dir(o) if not i.startswith('__')]
['append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'name',
'pop',
'remove',
'reverse',
'sort']
Can also use
__setitem__()
and
__getitem__()
as @
buran mention,
but it can more work that just inherit from list.