Sobes.tech
Middle

Tell me about the methods __getitem__, __setitem__, and __delitem__ in Python.

sobes.tech AI

Answer from AI

These methods relate to the Container Protocol and allow objects to support indexing, assignment by index, and deletion of elements by index, similar to lists or dictionaries.

__getitem__(self, key): Called when accessing an element of the object by key or index (e.g., obj[key]). The method should return the value of the element for the specified key.

// Example implementation of __getitem__
class MyContainer:
    def __init__(self, data):
        self._data = data

    def __getitem__(self, key):
        # Simple logic for getting by key
        print(f"Getting element by key: {key}")
        return self._data[key]

# Usage
container = MyContainer({'a': 1, 'b': 2})
print(container['a'])

__setitem__(self, key, value): Called when assigning a value to an element of the object by key or index (e.g., obj[key] = value). The method should set the value value for the element with key key.

// Example implementation of __setitem__
class MyContainer:
    def __init__(self, data):
        self._data = data

    def __setitem__(self, key, value):
        # Simple logic for setting by key
        print(f"Setting element by key {key} with value {value}")
        self._data[key] = value

# Usage
container = MyContainer({})
container['c'] = 3
print(container._data)

__delitem__(self, key): Called when deleting an element from the object by key or index (e.g., del obj[key]). The method should delete the element with key key from the object.

// Example implementation of __delitem__
class MyContainer:
    def __init__(self, data):
        self._data = data

    def __delitem__(self, key):
        # Simple logic for deletion by key
        print(f"Deleting element by key: {key}")
        del self._data[key]

# Usage
container = MyContainer({'d': 4, 'e': 5})
del container['d']
print(container._data)

These methods are often used when creating custom classes that should behave like sequences (lists, tuples, strings) or mappings (dictionaries). They allow providing an intuitive syntax for data access.