Providing Read-Only Attributes
Providing Read-Only Attributes. Probably the most elementary use case of
property() is to provide read-only attributes in your classes. Imagine you need an immutable
Point class that doesn’t allow the user to mutate the original value of its coordinates,
To achieve this goal, you can create a
Point class, as seen on-screen. Here you store the input arguments in the attributes
._y. As you learned earlier, using the leading underscore (
_) in names tells other developers that they’re non-public attributes and they shouldn’t be accessed directly using dot notation. Finally, you define two getter methods and decorate them with
Now you have two read-only properties,
.y, as your coordinates.
point.y are bare-bone examples of read-only properties. Their behavior relies on the underlying descriptor that
As you can see here, the default
.__set__() implementation raises an
AttributeError when you don’t define a proper setter method.
You can take this implementation of
Point a little bit further and provide explicit setter methods that raise a custom exception with more elaborate and specific messages.
Here, you define a custom exception called
WriteCoordinateError. This exception allows you to customize the way you implement your immutable
x.setter method raises a custom exception with a more explicit message. The implementation of the
y.setter method for the method follows the same pattern again, with a customized message for the
02:45 Note the difference in behavior when running the same code as seen earlier on in this section.
03:03 In the next section of the course, you’ll see how to extend this concept, creating attributes that have both read and write functionality.
Become a Member to join the conversation.