Dec-04-2019, 03:56 PM
The trick in Griboulis's code is the @property decorator. Decorators wrap the function immediately following it in another function to add some behavior to it. @property in particular creates an attribute with the name of the following function. The benefit of using @property is that it enables setter and getter methods all using the name of the attribute, "spam" in this case. Setters and getters can be used to run additional code when the attribute changes.
This is useful for attributes that need to be managed so that the object is correctly updated for the new value. For instance, if your class has an attributes that must correspond to get accurate results - say for car braking system - then you can have a managed attribute that will automatically change the other attributes when it is changed. Thereby, you can ensure everything is correctly updated whenever this critical value changes.
This is useful for attributes that need to be managed so that the object is correctly updated for the new value. For instance, if your class has an attributes that must correspond to get accurate results - say for car braking system - then you can have a managed attribute that will automatically change the other attributes when it is changed. Thereby, you can ensure everything is correctly updated whenever this critical value changes.
class Bar: def __init__(self): self._spam = 100 @property def spam(self): return self._spam @spam.setter def spam(self, value): print(self._spam) self._spam = value print(self._spam) @spam.getter def spam(self): return self._spam x = Bar() x.spam x.spam = 200 x.spam