使我们的自定义 class 支持 Python 中的数组括号 []

Make our custom class support array brackets [] in Python

由于 python 中的所有内容都与对象-class 模式相关,我们甚至可以使用运算符重载使我们的自定义 class 支持不同的运算符,例如 + - * /

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

我想知道是否有任何方式或方法可以覆盖,以便我们的自定义 class 可以支持 [],如列表、元组和其他可迭代对象:

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

在class中有一个叫做__getitem__的built-in函数,例如

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