To learn more about the concepts covered in this lesson, check out the following:
Creating Attributes With property()
Creating Attributes With
property(). You can create a property by calling
property() with an appropriate set of arguments and assigning its return value to a class attribute.
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.
First you create
Circle. The class initializer takes a radius as an argument and stores it in a non-public attribute called
Then you define three non-public methods:
._get_radius() returns the current value of
value as an argument and assigns it to
._del_radius() deletes the instance attribute
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.
Circle a try, save the code into
circle.py and run the following code in a Python shell. Note that in this course, the BPython shell will be used.
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
You can access the getter, setter, and deleter methods in a given property through the corresponding
Properties are also overriding descriptors. If you use
dir() to check the internal members of a given property, then you’ll find
.__get__() in the list.
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.
In the next section of the course, you’ll see the more popular use of
property() as a decorator.
Become a Member to join the conversation.