add a setter to a class in python

To add a setter to a class in Python, you can define a setter method inside the class definition using the @property decorator. Here's an example:

main.py
class MyClass:
    def __init__(self, value):
        self._value = value
    
    @property
    def value(self):
        return self._value
    
    @value.setter
    def value(self, new_value):
        self._value = new_value
228 chars
12 lines

In the example above, the @property decorator is used to define a getter method for a private variable _value. The @value.setter decorator is used to define a setter method for the same variable. Notice that the setter method has the same name as the getter method (value), but with the .setter suffix.

Here's how you can use the setter to change the value of an instance of the class:

main.py
obj = MyClass(42)
print(obj.value)  # output: 42

obj.value = 100
print(obj.value)  # output: 100
98 chars
6 lines

In the above example, we create an instance of MyClass with an initial value of 42. We then use the setter method to change the value to 100, and verify that the value has indeed changed by printing it again.

gistlibby LogSnag