Attribute Tips
Explore how to implement encapsulation in Python by hiding instance attributes and managing them via getters, setters, and properties. Understand the role of private attributes and how Python renames them to ensure safe manipulation. Learn to rely on boolean context rather than explicit True comparisons to write robust conditionals. This lesson helps you write safer, more modular Python code by mastering attribute control.
We'll cover the following...
Hide everything
One of the often-overlooked aspects of encapsulation is hiding instance attributes, or restricting direct access to an object’s inner machinery. Hidden attributes can’t be modified directly, which protects them from inconsistent modifications, both incidental and intentional. For example, if a class contains the radius of a circle and its area, we cannot change either attribute without changing the other:
Encapsulation
The general rule is to hide each instance attribute by making it private. The identifier of a private attribute begins with two underscores, such as __r and __area. A private attribute exists but isn’t visible outside of the class. We can’t observe it or mutate it other than by calling special methods: getters and setters. Presumably, a setter will check if the mutation operation is legal and execute it ...