Skip to content

Instantly share code, notes, and snippets.

@Nayemjaman
Created October 31, 2020 16:43
Show Gist options
  • Save Nayemjaman/13eec5311c07042197d97fa025709327 to your computer and use it in GitHub Desktop.
Save Nayemjaman/13eec5311c07042197d97fa025709327 to your computer and use it in GitHub Desktop.
A sample demonstration of __getitem__ in python class
""" __getitem__ in class example """
class Person:
def __init__(self):
# self.num_info = (1, 2, 3, 4, 5)
self.info = {
'name': 'Nayem Jaman',
'country': 'Bangladesh',
'mobile': 1234569
}
def __getitem__(self, i):
return self.info[i]
person = Person()
print(person.info['name'])
# print(person[3])
# utilizing __getitem__ method it can be written as
print(person['name'])
# print(person[3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment