Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Providing Read-Only Attributes

00:00 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, x and y.

00:22 To achieve this goal, you can create a Point class, as seen on-screen. Here you store the input arguments in the attributes ._x and ._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 @property.

01:06 Now you have two read-only properties, .x and .y, as your coordinates.

01:22 Here, point.x and point.y are bare-bone examples of read-only properties. Their behavior relies on the underlying descriptor that property provides.

01:33 As you can see here, the default .__set__() implementation raises an AttributeError when you don’t define a proper setter method.

01:44 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.

01:58 Here, you define a custom exception called WriteCoordinateError. This exception allows you to customize the way you implement your immutable Point class.

02:13 Here, the 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 y coordinate.

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.