python - 在 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
解决方案
有一个内置函数称为__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
推荐阅读
- django - X没有属性'object' - Django
- html - 按钮宽度 CSS 在移动设备上不会改变,但在桌面上很好
- python - Python - 键盘模块 - 线程问题
- android - 如何从 kotlin 中的内部对象类访问类级别变量
- unix - 在 unix 中查找匹配的文本并替换下两行
- symfony - 如何在 symfony 中恢复页面的先前路由名称
- java - 在 Linux 托管服务器上安装 Eclipse 时出错 - JVM 终止退出代码 =2
- python - 相关性背后的直觉
- regex - 使用 vim 和 regex 翻译代码注释
- python - 当我将小部件添加到第二个窗口时,PyQt5 崩溃了 python