Python Forum
How I can overload operator [] ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How I can overload operator [] ?
#1
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?
Reply
#2
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?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(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.
Reply
#4
Thanks everyone!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Overload of constructor psosmol 2 2,799 Apr-17-2019, 05:10 AM
Last Post: psosmol

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020