The purpose of this blog is to happily share my learning and ideas to help people, who actively seek solutions for the day-to-day problems faced.

Recent Posts

Python: Abstraction, Encapsulation - Explained

Attending a Python Interview ? You can't miss out below questions on Python's basic OOPS concepts,

  • Abstraction
  • Encapsulation

Both Abstraction and Encapsulation sounds similar and in general both of this hides something but the actual difference is how it hides details and at which level.

Abstraction and Encapsulation - Explained


Abstraction
It just gives you the abstract without including the implementation details i.e it hides details at the design level
Example: When we describe an object we inform in more abstract form, i.e Consider a vehicle which can move, here we didn't inform anything about how the vehicle moves whether its in a road, sails on the sea or flies in the air etc,.

Encapsulation
It just encapsulates the data and its related functions within an object definition i.e it hide details at the implementation level, it also restricts the access to some of the object's components.
Example1: Unlike other programming languages python doesn't provide any keywords for access modifiers; instead it uses '_' and '__' to define a variable as private (to prevent accidental modification of data) and thereby restricting it access to the outside world and enclosing this group of variables and its associated methods inside a class is nothing but Encapsulation.
Example2: Consider a scenario in which we consume a custom dictionary object from a pre-defined class, in this scenario the end user just updates the data (key,value) into the dict and gets the data as he wants, he doesn't care about how the dictionary is implemented say whether the dictionary is created using orderedDict (keys are ordered) or defaultDict (keys are assigned with default value).

Though Python considers we are adult and know how to deal with data, but still private variables can be accessed using, (Naughty boys :P but wait, why only boys ? Inequality bro !! )

  • Getters and Setters
  • Name Mangling

Getters and Setters
They are nothing but a methods available within the class and have access to private variables; whereas the end user can't directly access the private variables outside of the class (Mangling: Am I a joke to you ?)

Name Mangling
Using the name mangling technique we can still access the private variables but the class name should help :P ("__<className>_<attributeName>")

Example:
Please click on the below git hub links for example explained using python code,

No comments