Adding Behaviors to Class Data With Properties
Explore how to enhance class data management in Python by using properties, which allow attribute access with added validation and control. Learn to write cleaner, more maintainable code without changing interfaces when adding behaviors to attributes.
We'll cover the following...
Until now, we’ve focused on the separation of behavior and data. This is very important in object-oriented programming, but we’re about to see that, in Python, the distinction is uncannily blurry. Python is very good at blurring distinctions; it doesn’t exactly help us to think outside the box. Rather, it teaches us to stop thinking about the box.
Getter and setter methods
Before we get into the details, let’s discuss some bad object-oriented design principles. Many object-oriented developers teach us never to access attributes directly. They insist that we write attribute access like this:
The instance variables are prefixed with an underscore to suggest that they are private (other languages would actually force them to be private). Then, the get and set methods provide access to each variable. This class would be used in practice as follows:
The above example is not nearly as readable as the direct ...