Python Lessons – 7.5 Data Hiding

Python lessons - 7.5 Data Hiding

Data Hiding

One of the key parts of object-oriented programming is encapsulation, which involves the packaging of variables and related functions in one simple-to-use object: the instance of a class.

A concept related to this is data hiding, which consists in hiding the implementation details of a class. In this way the user interface of this class is clean and more intuitive. In other programming languages, data hiding is done by creating private methods and attributes, to which their external access to the function is blocked. In Python, however, the philosophy is slightly different “we are all consenting adults” and therefore there are no particular restrictions on access. So there is nothing that can deprive an attribute or method in such a way as to make it inaccessible to the outside of the classroom.

In Python, the so-called weakly-private methods have a single underscore (_) prefixed in their name. This prefix indicates the presence of a private method, which should not be used outside the class. But this is just a convention and nothing avoids the opposite. The only real effect it has is to avoid importing the method when using the wording

from modulename import *

Instead, there are methods and attributes, strongly private, that are distinguished by the double underscore (__) as prefix in their name. Once a method is marked with this double underscore, then the method will be really private and will no longer be accessible from outside the class.

However, these methods can still be accessed from the outside, but using a different name

_classname__privatemethodname

For example, if in a Figure class you have the private method __hidden you can access externally to this method by calling

_Figure__hidden

⇐Go to Python Lesson 7.4 – Object Lifecycle

Go to Python Lesson 7.6 – Class methods and static methods ⇒

Leave a Reply