Abstraction and Encapsulation in Python: Essential Concepts for Robust Programming
Table of Content:
Abstraction and Encapsulation
-
Abstractionmeans working with something you know how to use without knowing how it works internally. -
Encapsulationallows binding data and associated methods together in a unit i.e class. -
These principles together allows a programmer to define an interface for applications, i.e. to define all tasks the program is capable to execute and their respective input and output data.
-
A good example is a television set. We don’t need to know the inner workings of a TV, in order to use it. All we need to know is how to use the remote control (i.e the interface for the user to interact with the TV).
Abstracting Data
-
Direct access to data can be restricted by making required attributes or methods private, just by prefixing it's name with one or two underscores.
-
An attribute or a method starting with:
no underscoresis apublicone.a single underscoreisprivate, however, still accessible from outside.double underscoresisstrongly privateand not accessible from outside.
Abstraction and Encapsulation Example
empidattribute ofEmployeeclass is made private and is accessible outside the class only using the methodgetEmpid.
class Employee(Person):
all_employees = EmployeesList()
def __init__(self, fname, lname, empid):
Person.__init__(self, fname, lname)
self.__empid = empid
Employee.all_employees.append(self)
def getEmpid(self):
return self.__empid
Abstraction and Encapsulation Example Contd..
e1 = Employee('Jack', 'simmons', 456342)
print(e1.fname, e1.lname)
print(e1.getEmpid())
print(e1.__empid)
Output
Jack simmons
456342
AttributeError: Employee instance has no attribute '__empid'