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 refer to our video player troubleshooting guide for assistance.

Creating Backwards-Compatible APIs

00:00 Creating Backwards-Compatible Class APIs. As you already know, properties turn method calls into direct attribute lookups. This feature allows you to create clean and Pythonic APIs for your classes.

00:16 You can expose your attributes publicly without the need for getter and setter methods. If you ever need to modify how you compute a given public attribute, then you can turn it into a property. Properties make it possible to perform extra processing, such as data validation, without having to modify your public APIs.

00:37 Let’s say you’re creating an accounting application and you need a base class to manage currencies. To this end, you create a Currency class that exposes two attributes, .units and .cents.

01:08 This class looks clean and Pythonic. Now say that your requirements change, and you decide to store the total number of cents instead of the units and cents.

01:18 Removing .units and .cents from your public API to use something such as .total_cents would break more than one client’s code. In this situation, property() can be an excellent option to keep your current API unchanged.

01:32 Here’s how you can work around the problem and avoid breaking your clients’ or your own code.

02:33 Now your class stores the total number of cents instead of independent units and cents. However, your users can still access and mutate .units and .cents in their code and get the same results as before.

02:50 When you write something upon which many people are going to build, you need to guarantee that modifications to the internal implementation don’t affect how end users work with your classes.

03:02 In the next section of the course, you’ll see how it’s possible to override properties when making use of subclasses in Python.

Become a Member to join the conversation.