Ask Your Question
2

How to include a __getitem__ method as an accessor to a class in Python?

asked 2023-07-08 10:09:12 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-08 10:17:01 +0000

nofretete gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-08 10:09:12 +0000

Seen: 10 times

Last updated: Jul 08 '23