Skip to content
Minsing Log
Go back

English Edition

Python getter → What Is __getitem__?

Programming & CS

__getitem__ is a method in Python that is called when an object is indexed (obj[key]) or sliced (obj[start:stop]). Defining this method inside a class allows instances of that class to be used like lists or dictionaries.


📌 Basic Usage

class MyList:
    def __init__(self, data):
        self.data = data

    def __getitem__(self, index):
        print(f"Called with index: {index}")
        return self.data[index]

my_list = MyList([10, 20, 30])
print(my_list[1])  # => Called with index: 1
                   # => 20

🎯 Key Features


✅ Slicing Can Also Be Supported

class MyList:
    def __init__(self, data):
        self.data = data

    def __getitem__(self, index):
        print(f"Index received: {index}")
        return self.data[index]

lst = MyList([1, 2, 3, 4, 5])
print(lst[1:4])  # 슬라이스 객체(slice(1,4,None))가 전달됨

📦 Example: Mimicking a Two-Dimensional Array

class Matrix:
    def __init__(self, rows):
        self.rows = rows

    def __getitem__(self, index):
        return self.rows[index]

m = Matrix([[1, 2], [3, 4]])
print(m[0][1])  # 2

⚠️ Notes

If you’re curious, I can also explain __setitem__ and __delitem__. Would you like to learn more?

Follow the journey

Get new posts by email.

Short, honest notes on building, startups, learning, failures, and retrospectives, for readers who follow the journey rather than pass through from search.

The newsletter is coming soon. Until then, follow via RSS or email me to get notified.


Share this post:

Comments

Sign in with GitHub to leave a comment.


Previous Post
Mean pooling - Let's match the embedding dimensions
Next Post
How to Map a Func to Elements of Multiple Nested Data Structures