Python Forum

Full Version: How I can overload operator [] ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Python 3.7.2

I created my own class- collection ​​and I don’t want to write the add method everywhere when adding elements in my collection. How I can use the familiar square bracket operator?
The special method you are looking for is object.__setitem__(). Probably you will want to implement also object.__getitem__().
However, do you really need to overload it? Does your class inherit from some built-in class?
(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 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.
Thanks everyone!