Python Object Oriented Programming | Data Hiding

Data hiding states that implementation details of a class should be hidden, and a clean standard interface be presented for those who want to use the class.

Weakly private methods and attributes have a single underscore at the beginning.
This signals that they are private, and shouldn’t be used by external code. However, it is mostly only a convention, and does not stop external code from accessing them.

Its only actual effect is that from module_name import * won’t import variables that start with a single underscore.

Example:

class Queue:
	def __init__(self, contents):
		self._hiddenlist = list(contents)

	def push(self, value):
		self._hiddenlist.insert(0, value)

	def pop(self):
		return self._hiddenlist.pop(-1)

	def __repr__(self):
		return "Queue({})".format(self._hiddenlist)

queue = Queue([1, 2, 3])
print(queue)
queue.push(0)
print(queue)
queue.pop()
print(queue)
print(queue._hiddenlist)

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
Queue([1, 2, 3])
Queue([0, 1, 2, 3])
Queue([0, 1, 2])
[0, 1, 2]
ddn_ro@linux:~/Desktop$

In the code above, the attribute _hiddenlist is marked as private, but it can still be accessed in the outside code.
The __repr__ magic method is used for string representation of the instance.

Strongly private methods and attributes have a double underscore at the beginning of their names. This causes their names to be mangled, which means that they can’t be accessed from outside the class.

The purpose of this isn’t to ensure that they are kept private, but to avoid bugs if there are subclasses that have methods or attributes with the same names.

Name mangled methods can still be accessed externally, but by a different name. The method __privatemethod of class Spam could be accessed externally with _Spam__privatemethod.

Example:

class Vehicle:
	__car = "Audi"
	def print_car(self):
		print(self.__car)

v = Vehicle()
v.print_car()
print(v._Vehicle__car)
print(v.__car)

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
Audi
Audi
Traceback (most recent call last):
  File "file.py", line 9, in 
    print(v.__car)
AttributeError: Vehicle instance has no attribute '__car'
ddn_ro@linux:~/Desktop$

Note:
Python protects those members by internally changing the name to include the class name.

Leave a Reply