__setitem__ in Python: Custom logic for square-bracket assignment

__setitem__ in Python: Custom logic for square-bracket assignment

Let users assign using [] in Python, with custom logic with __setitem__:

class StringList:
    def __init__(self, d):
        self.d = d
    def __setitem__(self, i, v):
        self.d[i] = str(v)
sl = StringList(['2', '4', '6', '8'])
sl[2] = 99

sl.d
[‘2’, ‘4’, ’99’, ‘8’]