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.
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,
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.
.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.
Now your class stores the total number of cents instead of independent units and cents. However, your users can still access and mutate
.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.