Pages

Wednesday, June 18, 2025

How does __getitem__ enable sequence-like behavior in a class?

All Questions From This Chapter

__getitem__ to enable sequence-like behavior

The __getitem__ method enables sequence-like behavior in a Python class by allowing you to access items in the object using square bracket notation—just like you do with lists, tuples, or strings.


✅ What it does:

When you define __getitem__(self, key) in your class:

  • Python calls this method whenever you do obj[key]

  • You can support:

    • Indexing (obj[0])

    • Slicing (obj[1:4])

    • Even complex keys like tuples (obj[1, 2])


📦 Example:

python
class MySequence: def __init__(self, data): self.data = data def __getitem__(self, index): return self.data[index] seq = MySequence([10, 20, 30, 40]) print(seq[1]) # 20 print(seq[1:3]) # [20, 30]

🔁 What it enables:

  • Looping with for item in obj

  • Indexing and slicing

  • Compatibility with len(), in, enumerate(), etc. (if other methods like __len__ and __iter__ are also defined)


🧠 Summary:

Implementing __getitem__ turns your class into an indexable and iterable object, giving it familiar behavior like Python’s built-in sequences.

Tags: Technology,Python,Interview Preparation,

No comments:

Post a Comment