logo

Python Special Method __getitem__ 📂Programing

Python Special Method __getitem__

Summary

__getitem__ is the method that allows an object to be indexed.

Description

__getitem__ is one of Python’s special methods, enabling instances of a class to access specific elements using square brackets [], like lists or dictionaries.

When we retrieve values from a list or dictionary using obj[key] or obj[index], Python internally calls the object’s obj.__getitem__(key). Therefore, if a user-defined custom class implements this method, intuitive data access becomes possible in the same manner as Python’s built-in sequence types.

Code

class CustomData:
    def __init__(self, data):
        self.data = data
        
    def __getitem__(self, index):
        print(f"인덱스 {index}에 접근했습니다.")
        return self.data[index]

# 객체 생성
>>> a = CustomData([10, 20, 30, 40, 50])

# 단일 인덱싱
>>> a[2]
인덱스 2에 접근했습니다.
30

# 슬라이싱
>>> a[1:4]
인덱스 slice(1, 4, None)에 접근했습니다.
[20, 30, 40]

As shown in the code above, calling a[2] internally executes a.__getitem__(2), returning the value along with the predefined print statement. When slicing is used, as in a[1:4], __getitem__ is also invoked; in that case a slice object, not an integer, is passed as the argument.

Environment

  • Windows 11
  • Python 3.10.11