Encapsulation

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 Beyond the Basics – Object-Oriented Programming

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.

If you run the program you see:

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:

This then outputs the variables values:

The class with private attribute and methods.

encapsulation

The values are changed within the class methods. You could do additional checks, like if the value is not negative or to large.

Previous Post
Next Post

Leave a Reply