0

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
Ashkan Khademian
  • 307
  • 3
  • 12
  • https://docs.python.org/3/reference/expressions.html#subscriptions – wwii Oct 03 '20 at 23:46
  • Related: [Implementing slicing in __getitem__](https://stackoverflow.com/questions/2936863/implementing-slicing-in-getitem), – wwii Oct 03 '20 at 23:51

1 Answers1

1

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
Ozballer31
  • 413
  • 1
  • 5
  • 14