Using property() as a Decorator
With a decorator, you can attach pre- and post-processing operations to an existing function. As you can see on-screen, the decorator syntax consists of placing the name of the decorator function with a leading
@ symbol right before the definition of the function you want to decorate. In this code,
@decorator can be a functional class intended to decorate the function.
The decorator approach for creating properties requires defining a first method using the public name for the underlying managed attribute, which is
.radius in this case. This method should implement the getter logic.
Take another look at the
dir() output, of which a selected portion is shown on the slide on-screen. Besides
.fdel, and a bunch of other special attributes and methods,
property also provides
.setter(). These three methods each return a new property.
This new property contains the same set of methods of the initial property, with the addition of the new setter method. Finally, the decorator syntax reassigns the new property to the
.radius class-level name.
The mechanism to define the deleter method is similar. This time you need to use the
@radius.deleter decorator. At the end of the process, you get a full-fledged property with the getter, setter, and deleter methods.
One question that may arise is how you can provide suitable docstrings for your properties when you use the decorator approach. If you look at
Circle on-screen, you’ll note that you’ve already done so by adding a docstring to the getter method.
This code looks fairly different from the getter and setter methods approach.
Circle now looks more Pythonic and clean. You don’t need to use method names such as
If you check your
Circle implementations so far, then you’ll note that their getter and setter methods don’t add any real processing on top of your attributes. In general, you should avoid turning attributes that don’t require extra processing into properties.
Unless you need something more than bare attribute access, don’t write properties. They’re a waste of CPU time, and more importantly, they’re a waste of your time. Finally, you should avoid writing explicit getter and setter methods and then wrapping them up in a property. Instead, use the
Become a Member to join the conversation.