# 示例代码:Python 中的 __getitem__ 和 __setitem__ 方法
class MyList:
def __init__(self, initial_data):
self.data = initial_data
def __getitem__(self, index):
"""实现对对象使用 [] 操作符进行索引访问"""
return self.data[index]
def __setitem__(self, index, value):
"""实现对对象使用 [] 操作符进行赋值"""
self.data[index] = value
# 创建一个 MyList 对象
my_list = MyList([1, 2, 3, 4, 5])
# 使用 __getitem__ 访问元素
print(my_list[0]) # 输出: 1
# 使用 __setitem__ 修改元素
my_list[0] = 10
print(my_list[0]) # 输出: 10
__getitem__ 方法允许我们通过索引访问对象中的元素,类似于列表或字典的操作。__setitem__ 方法允许我们通过索引修改对象中的元素。[] 来访问和修改元素。上一篇:python有趣的代码
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站