Getting Started With property()
This function allows you to turn class attributes into properties or managed attributes. Since
property() is a built-in function, you can use it without importing anything. Additionally,
property() was implemented in C to ensure optimal performance.
Note that it’s common to refer to
property() as a built-in function. However,
property is a class designed to work as a function rather than as a regular class. That’s why most Python developers call it a function.
That’s also the reason why
property() doesn’t follow the Python convention for naming classes. This course follows the common practices of calling
property() a function rather than a class. With
property(), you can attach getter and setter methods to a given class attribute. This way, you can handle the internal implementation for that attribute without exposing getter and setter methods in your API.
The first two arguments take function objects that will play the role of getter (
fget) and setter (
fget is a function that returns the value of the managed attribute,
fset is the function that allows you to set the value of the managed attribute,
fdel is a function to define how the managed attribute handles deletion, and
doc is a string representing the property’s docstring.
You can use
property() as either a function or a decorator to build your properties. In the next two sections of the course, you’ll see how to use both approaches, starting with using
property() as a function.
Become a Member to join the conversation.