首页 > 解决方案 > 在 Python 中让我们的自定义类支持数组括号 []

问题描述

由于python中的每一件事都与对象类模式有关,我们甚至可以让我们的自定义类支持不同的运算符,比如+ - * /使用运算符重载,例如

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

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

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

标签: pythonarrayslistcustom-lists

解决方案


有一个内置函数称为__getitem__类,例如

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

推荐阅读