Getting Started With property()
00:00
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.
00:12
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.
00:28
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.
00:41
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.
01:07
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 property().
01:20
The first two arguments take function objects that will play the role of getter (fget) and setter (fset) methods. 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.
01:48
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 fget().
02:00
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.
02:08
Finally, if you delete it, as seen on-screen (del obj.attr), then Python automatically calls fdel().
02:17
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.
02:28
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 help().
02:38
The doc argument is also useful when you’re working with code editors and IDEs that support docstring access.
02:46
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.
