An objects variables should not always be directly accessible.
To prevent accidental change, an objects variables can sometimes only be changed with an objects methods. Those type of variables are private variables.
The methods can ensure the correct values are set. If an incorrect value is set, the method can return an error.
Related course: Python Programming Courses & Exercises
Encapsulation example
Python does not have the private keyword, unlike some other object oriented languages, but encapsulation can be done.
Instead, it relies on the convention: a class variable that should not directly be accessed should be prefixed with an underscore.
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
Private variables are intended to be changed using getter and setter methods. These provide indirect access to them:
class Robot(object): |
This then outputs the variables values:22
23
The class with private attribute and methods.
The values are changed within the class methods. You could do additional checks, like if the value is not negative or to large.
If you are a Python beginner, then I highly recommend this book.
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.