To learn more about the concepts covered in this lesson, check out the following:
Creating Attributes With property()
All of the arguments to
property() are optional. However, you typically provide at least a setter function. The example seen on-screen shows how to create a
Circle class with a handy property to manage its radius.
Once you have these three methods in place, you create a class attribute called
.radius to store the property object. To initialize the property, you pass the three methods as arguments to
01:31 You also pass a suitable docstring for the property. In this example, you use keyword arguments to improve the code readability and prevent confusion. That way, you know exactly which method goes into which argument.
It offers several improvements over the standard shell, including color-coding and an improved help reader. But note that all of the commands that you see will run in the standard Python shell, which is typically accessed by typing
python at the command line.
First, you import the
Circle class, and then create an instance with a radius of
.radius property hides the non-public instance attribute
._radius, which is now your managed attribute in this example. You can access and assign
Internally, Python automatically calls
._set_radius() when needed. When you execute the next command (
del circle.radius), Python calls
._del_radius, which deletes the underlying
Properties are class attributes that manage instance attributes. You can think of a property as a collection of methods bundled together. If you inspect
.radius carefully, then you can find the raw methods you provided as a
These methods provide a default implementation of the descriptor protocol. If you want to better understand the internal implementation of
property as a class, then follow the link on-screen to read about the pure Python
property class described in the documentation.
Become a Member to join the conversation.