Module (77%)
Section (40%)

Let's start with a few analogies from real life:

washing machine

Imagine a washing machine door ( object ) that protects access to your laundry ( attribute values ) while your appliance is washing it ( processing ). You have a set of controls ( methods ) that allow you to manage your laundry, or even see it (many wash machines are equipped with a transparent window).

So, while the washing machine is processing your laundry, you are not able to directly access the laundry. This is how attribute encapsulation works.

bank

Another good example is a money bank; this time it’s a more IT-related example:

When your money ( attribute value ) is deposited in the bank account ( object ), you cannot access it directly and without some checks or security. This is a basic countermeasure to protect your account from withdrawals exceeding certain limits or the account balance. But you can always make use of some dedicated interfaces (methods like a mobile application or a web application) to spend money up to an appropriate amount.


Attribute encapsulation can be also used to limit unauthorized access: reading and modifying the account balance. Remember that this is not full access control, the programmer can still get access to your attributes intentionally as Python does not deliver true privacy.

Why?

Guido Van Rossum, best known as the author of Python, once said: "We're all consenting adults here" justifying the absence of such access restrictions.

So, if your code does intentionally access the attributes marked as private (prefixed with a double underscore) in a direct way, then remember that this behavior is unpythonic.

water tank

The last example could be presented with the behavior of a class representing a water or fuel tank:

It would not be wise to pour any amount of liquid directly into the tank ( object ) exceeding the total tank capacity, or request setting the liquid level to a negative value.