__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:
🔁 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.
No comments:
Post a Comment