__getitem__
时间: 2023-10-22 13:05:22 浏览: 45
__getitem__ is a method in Python that allows objects to be indexed or sliced like sequences. It is often used in conjunction with the __len__ method to define custom container classes.
When an object is indexed or sliced using square brackets [], Python will call the object's __getitem__ method with the specified index or slice object as an argument. The __getitem__ method should then return the corresponding value or slice of values.
Here is an example implementation of __getitem__ for a custom container class:
```
class MyList:
def __init__(self, *args):
self.data = list(args)
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return len(self.data)
my_list = MyList(1, 2, 3, 4, 5)
print(my_list[2]) # Output: 3
print(my_list[1:4]) # Output: [2, 3, 4]
```