Getting Started With property()
Getting Started With Python’s
property(). As you’ve seen, Python’s
property() is the Pythonic way to avoid formal getter and setter methods in your code.
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.
You can also specify a way to handle attribute deletion and provide an appropriate docstring for your properties. On-screen, you can see the full signature of
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.
The return value of
property() is the managed attribute itself. If you access the managed attribute, as seen on-screen (
obj.attr), then Python will automatically call
If you assign a new value to the attribute, again as seen on-screen (
obj.attr = value), then Python calls
fset() using the input
value as an argument.
Finally, if you delete it, as seen on-screen (
del obj.attr), then Python automatically calls
Note that the first three arguments to
property() take function objects. You can think of a function object as the function name without the calling pair of parentheses.
You can use
doc to provide an appropriate docstring for your properties. You and your fellow programmers will be able to read that docstring using Python’s
doc argument is also useful when you’re working with code editors and IDEs that support docstring access.
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.