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 your subtitle preferences 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-Write Attributes

00:00 Providing Read-Write Attributes. You can also use property() to provide managed attributes with read-write capabilities. In practice, you just need to provide the appropriate getter method (“read”) and setter method (“write”) to your properties in order to create read-write managed attributes.

00:23 Let’s say you want your Circle class to have a .diameter attribute. However, taking the radius and the diameter in the class initializer seems unnecessary because you can compute one using the other.

00:37 Here’s a Circle that manages .radius and .diameter as read-write attributes.

01:08 The setter method converts the input value for the radius and assigns it to the non-public ._radius, which is the variable you use to store the final data.

01:17 The getter method just returns the radius value, which has been stored in the non-public ._radius. There’s a subtle detail to note in this new implementation of Circle and its .radius attribute. In this case, the class initializer assigns the input value to the .radius property directly instead of storing it in a dedicated non-public attribute, such as ._radius.

01:43 This is to ensure that every value provided as a radius, including the initialization value, goes through the setter method and gets converted to a floating-point number.

01:55 Here, Circle also implements a .diameter attribute as a property. The getter method computes the diameter using the radius. The setter method is worth examination.

02:07 Instead of storing the input diameter value in a dedicated attribute, it calculates the radius and writes the result into .radius.

02:19 Here, you can see Circle in action.

02:28 Both .radius and .diameter work as normal attributes in these examples, providing a clean and Pythonic public API for your Circle class.

02:49 In the next section of the course, you’ll see how to provide another combination of functionality, providing write-only attributes.

Become a Member to join the conversation.