Attribute Tips
Learn how to hide attributes from the outer world in Python.
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:
class Circle:def __init__(self, r):self.r = rself.area = math.pi * r * rmy_circle = Circle(10)my_circle.r = -20 # Oh, no! The area did not change.print(my_circle.area)
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 ... ...