Professional Documents
Culture Documents
How To Use Encapsulation in Python
How To Use Encapsulation in Python
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.
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.
PYTHON
class Robot(object):
def __init__(self):
self.a = 123
self._b = 123
self.__c = 123
obj = Robot()
print(obj.a)
print(obj._b)
print(obj.__c)
PYTHON
123
123
Traceback (most recent call last):
File "test.py", line 10, in <module>
print(obj.__c)
AttributeError: 'Robot' object has no attribute '__c'
A single underscore: Private variable, it should not be accessed directly. But nothing stops
you from doing that (except convention).
Private variables are intended to be changed using getter and setter methods. These
provide indirect access to them:
PYTHON
class Robot(object):
def __init__(self):
self.__version = 22
def getVersion(self):
print(self.__version)
obj = Robot()
obj.getVersion()
obj.setVersion(23)
obj.getVersion()
print(obj.__version)
PYTHON
https://pythonprogramminglanguage.com/encapsulation/ 2/4
4/5/2021 How to use Encapsulation in Python - Python
22
23
The values are changed within the class methods. You could do additional checks, like if
the value is not negative or to large.
Download exercises
Leave a Reply:
Email address
Message
Send Message
obj = Robot()
obj.getVersion()
obj.setVersion(23)
obj.getVersion()
print(obj.__version)
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.
However you would see 3 values printed if you remove all the underscores.
© 2021 https://pythonprogramminglanguage.com
https://pythonprogramminglanguage.com/encapsulation/ 4/4