Data hiding in Python
Coding with Python
🕑 This lesson will take about 20 minutes
Data hiding (also known as encapsulation) is a technique used in object-oriented programming (OOP) to hide the details of an object and function. Data hiding helps to protect the integrity of objects by preventing unintended changes to the object’s variables (or attributes).
In Python, attributes and methods that belong to a class can be:
public,
private, or
protected
Public
By default, all attributes and methods in a Python class are considered public, meaning they can be accessed from outside the class (anywhere in the program). In the example code below, there is an attribute and a method defined inside the class MyClass. Both public_attribute and public_method can be accessed from outside the MyClass class.
Private
In Python, if an attribute’s or method’s name begins with two underscores (__), then the attribute or method is considered private. The attribute or method is still accessible, but its name is changed in a way that makes it harder to access accidentally, and attempting to access the attribute or method from outside the class will result in an AttributeError. Private methods can protect objects from unintended changes to the object’s variables (or attributes). Instead, you can create methods specifically designed for accessing and modifying an object’s variables. These methods may restrict how object variables can be accessed or validate changes to object variables to ensure only intended or accurate changes are made to them.
In the example code below, the MyClass class has a private attribute and a private method. Attempting to access the private method or attribute, or modify the private attribute from outside the class, will result in an AttributeError. However, three public methods have been created that allow the programmer to use the private method or access or modify the private attribute via these public methods.
Protected
Python has no strict mechanism for protected attributes and methods like some other languages such as Java. However, by convention, attributes and methods that are given a name beginning with a single underscore (_) are considered protected, meaning they should not be accessed directly from outside the class. However, there are no technical limitations preventing these attributes or methods from being accessed.
The single underscore at the beginning of an attribute or method name is more of a convention, indicating to a programmer that these attributes or methods should not be accessed outside the class, however, there is nothing technically stopping them from being accessed.