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):
def __init__(self):
self.a = 123
self._b = 123
self.__c = 123

obj = Robot()

If you run the program you see:

Traceback (most recent call last):
File "", line 10, in <module>
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):
def __init__(self):
self.__version = 22

def getVersion(self):

def setVersion(self, version):
self.__version = version

obj = Robot()

This then outputs the variables values:


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.

Download exercises