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.py228 chars12 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.py98 chars6 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