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?
__getitem__use in your example doesn't make a lot of sense, but imagine that you need to write a custom list- or dictionary-like class, that has to work with existing code that uses[]. That's a situation where__getitem__is useful. - Pieter Witvoetplanets[i]to access a given item even thoughplanetsis not actually a list (and it could, under the covers, use any data structure it chooses, such as a linked list or graph, or implement any non-list functions that it chooses, which a list could not). - jarmod