Encapsulation means keeping the inside of an object private. The outside of the program uses the object through its methods, and cannot reach the variables directly.
That sounds like extra work, and it is, but it pays off the moment you have to change how a value is stored. Only one method has to change.
Sometimes you want the variables of an object to change only through its methods. Those variables are private.
The method can check the value first and complain if it is wrong.
Encapsulation example
Python does not have the private keyword, unlike some other object oriented languages, but encapsulation can be done.
It uses a convention instead: a name with one leading underscore should not be used from outside the class.
class Robot(object): |
If you run the program you see:123
123
Traceback (most recent call last):
File "test.py", line 10, in <module>
print(obj.__c)
AttributeError: 'Robot' object has no attribute '__c'
So what’s with the underscores and error?
A single underscore: Private variable, it should not be accessed directly. But nothing stops you from doing that (except convention).
A double underscore: Private variable, harder to access but still possible.
Both are still accessible: Python has private variables by convention.
Getters and setters
Getter and setter methods are the usual way to reach a private variable:
class Robot(object): |
This then outputs the variables values:22
23
The class with private attribute and methods.
The method can do more than store the value. It can refuse a negative number or a number that is too big.
How Python does it
- A name with one leading underscore,
self._name, is private by convention. Nothing stops you using it from outside, it is a promise between programmers. - A name with two leading underscores,
self.__name, gets name mangled. Python rewrites it to_ClassName__name, so the outside cannot use the same name by accident. self.__nameis still reachable asobj._ClassName__name. It stops mistakes, not a determined attacker.- Use
@propertyto give a private variable a getter and a setter, so reading and writing still work but you control what happens.
The reason to bother is validation. A setter can refuse a bad value, so no code path leaves the object in a broken state.
The fastest way to learn this is to write it yourself. The PyChallenge exercises run in your browser, no install needed.

This code should print 3 values.
Isn't it?
Just two, the last line isn't allowed as it's a private variable of the class Robot. It has two underscores which doesn't allow the variable to be accessed outside the class.
You'd see this error:
However you would see 3 values printed if you remove all the underscores.