Abstraction and Encapsulation
Table of Content:
Abstraction and Encapsulation
-
Abstraction
means working with something you know how to use without knowing how it works internally. -
Encapsulation
allows 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 underscores
is apublic
one.a single underscore
isprivate
, however, still accessible from outside.double underscores
isstrongly private
and not accessible from outside.
Abstraction and Encapsulation Example
empid
attribute ofEmployee
class 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'