pythonarrayslistcustom-lists

Make our custom class support array brackets [] in Python


Since every thing in python is related to object-class pattern We can even make our custom class support different operators like + - * / using operator overloading e.g.

class CustomClass:
    def __init__(self):
        # goes some code
        pass
    
    def __add__(self, other):
        # goes some code so that our class objects will be supported by + operator
        pass

I wanted to know is there any way or any methods to override so that our custom class could support [] like lists, tuples and other iterables:

my_list = [1, 2, 4]
x = my_list[0]
# x would be 1 in that case

Solution

  • There is a built-in function called __getitem__ of class, for example

    class CustomList(list):
        """Custom list that returns None instead of IndexError"""
        def __init__(self):
            super().__init__()
    
        def __getitem__(self, item):
            try:
                return super().__getitem__(item)
            except IndexError:
                return None
    
    
    custom = CustomList()
    custom.extend([1, 2, 3])
    print(custom[0]) # -> 1
    print(custom[2 ** 32]) # -> None