Course contentsShow
← Python
Lesson 454 of 1,0607. Object-Oriented ProgrammingFree lesson

Implementing Container Access Protocols

Define __getitem__, __setitem__, and __delitem__ to allow your objects to support indexing, slicing, and item assignment syntax.

In this lesson, you will learn how to make your custom objects behave like built-in containers—such as lists or dictionaries—by implementing specific "magic" methods that respond to index and key-based syntax.

The Container Access Protocol

In Python, objects don’t automatically support square bracket notation (like obj[key]). To enable this behavior, your class must implement the "container protocol" using three special methods:

  • __getitem__(self, key): Called when you access an item, e.g., value = my_obj[key].
  • __setitem__(self, key, value): Called when you assign a value, e.g., my_obj[key] = value.
  • __delitem__(self, key): Called when you delete an item, e.g., del my_obj[key].

By defining these, you translate standard Python syntax into specific instructions for your object’s internal storage.

Putting it into Practice

Imagine you are building a SmartLibrary class that tracks books. Instead of forcing users to call get_book(id), you can let them use index syntax:

class SmartLibrary:
    def __init__(self):
        self._books = {}

    def __getitem__(self, book_id):
        return self._books[book_id]

    def __setitem__(self, book_id, title):
        self._books[book_id] = title

    def __delitem__(self, book_id):
        del self._books[book_id]

# Usage:
library = SmartLibrary()
library[101] = "Learning Python"  # Triggers __setitem__
print(library[101])              # Triggers __getitem__
del library[101]                 # Triggers __delitem__

Why use this?

When you implement these methods, your objects become intuitive for other developers to use. This protocol even supports slicing. If key is a slice object (e.g., my_obj[0:5]), __getitem__ receives that slice object, allowing you to return a range of items from your internal storage.

By defining these three methods, you move your custom classes beyond simple data containers and into full-fledged, professional-grade objects that integrate seamlessly with Python’s expected behaviors.

Key Takeaway: Implementing __getitem__, __setitem__, and __delitem__ allows your custom objects to use square bracket syntax, effectively mimicking the interface of native Python collections.