Search code examples
pythondecoratorgetter-setterpython-decoratorsmagic-methods

On defining a setter in Python


Let's say we have the following code:

class A:
       def __init__(self):
           self.x = [p for p in range(10)]
        
       def __getitem__(self, key):
           return self.x[key]

a = A()
print a[2] #will return a.x[2] = 2

Now how can I define the setter for a[i]? How will I define the decorator?

The process for a simple property is really simple but how will Python understand, in this case, that I want to define a setter for a[i] (something like @a[i].setter) ?


Solution

  • You don't have any decorators in your code, nor do you need one to support item assignment.

    Just implement the object.__setitem__() method for your class:

    class A:
        def __init__(self):
            self.x = [p for p in range(10)]
    
        def __getitem__(self, key):
            return self.x[key]
    
        def __setitem__(self, key, value):
            self.x[key] = value