1 | initial version |
To include a __getitem__
method as an accessor to a class in Python, you need to define the method inside the class definition. Here's an example:
class MyClass:
def __init__(self, data):
self.data = data
def __getitem__(self, key):
return self.data[key]
In this example, the __init__
method initializes the instance variable data
with the given data. The __getitem__
method returns the value of the data
instance variable at the given index, which is specified by the key
parameter.
Now you can create an instance of the class and access its data using the square bracket notation, like this:
my_obj = MyClass([1, 2, 3, 4])
print(my_obj[2]) # Output: 3
In this example, my_obj[2]
will access the third element of the data
list, which is 3
.