def __getitem__(self, idx)
时间: 2023-11-06 10:32:49 浏览: 36
# This is a special method in Python classes that allows instances of the class to behave like arrays or lists.
# When an instance of the class is accessed using square brackets like instance[idx], this method is called
# with idx as the index that was accessed. The method should return the value at that index.
# Here is an example implementation for a class MyList that stores a list of integers:
class MyList:
def __init__(self, lst):
self.lst = lst
def __getitem__(self, idx):
return self.lst[idx]
# With this implementation, we can create an instance of MyList and access its elements like a regular list:
my_list = MyList([1, 2, 3, 4, 5])
print(my_list[0]) # Output: 1
print(my_list[2]) # Output: 3
print(my_list[-1]) # Output: 5
# Note that if the index is out of range, Python will raise an IndexError exception, just like with regular lists.