[Python] Understanding __getitem__ method in Python

Discussão em 'Python' iniciado por Stack, Janeiro 31, 2025.

  1. Stack

    Stack Membro Participativo

    I have gone through most of the documentation of __getitem__() in the Python docs, but I am still unable to grasp the meaning of it.

    So all I can understand is that __getitem__() is used to implement calls like self[key]. But what is the use of it?

    Lets say I have a python class defined in this way:

    class Person:
    def __init__(self,name,age):
    self.name = name
    self.age = age

    def __getitem__(self,key):
    print ("Inside `__getitem__` method!")
    return getattr(self,key)

    p = Person("Subhayan",32)
    print (p["age"])


    This returns the results as expected. But why use __getitem__() in the first place? I have also heard that Python calls __getitem__() internally. But why does it do it?

    Can someone please explain this in more detail?

    Continue reading...

Compartilhe esta Página