41 Encapsulation in python
'''
1. Encapsulation is the process of wrapping up variables and methods into
a single entity.
In programming, a class is an example
that wraps all the variables and methods defined inside it.
class One():
name = 'umamahesh'
def add(self):
print(' ADD is ')
def sub(self):
print(' SUB is:')
ins = One()
print('\n ', ins.name)
--Using encapsulation we can give protection to the class members.
It can achieve Using access modifiers.
Encapsulation can be achieved using Private and Protected Access Members.
'''
Example---CSE department faculty cannot access the ECE department student record and
so on. Here, the department acts as the class and
student records act like variables and methods.
=======Why Do We Need Encapsulation?===========
===Encapsulation acts as a protective layer by ensuring that,
access to wrapped data is not possible by any code defined outside the class
in which the wrapped data are defined.
====Encapsulation provides security by hiding the data from the outside world.
---In Python, Encapsulation can be achieved by
declaring the data members of a class either as private or protected.
---- In Python, 'Private' and 'Protected' are called Access Modifiers,
as they modify the access of variables or methods defined in a class.
Let us see how access modifiers help in achieving Encapsulation.
---Encapsulation Using Private Members---
class rectangle:
__l=0
__b=0
def __init__(self):
self.__l=5
self.__b=3
print(self.__l)
r=rectangle()
print(r.l)
-----Encapsulation Using Protected Members---
class Shape:
_length = 10
_breadth = 20
class rectangle(Shape):
def __init__(self):
print(self._length)
print(self._breadth)
cr = rectangle()
#printing protected variablesoutsidethe class 'Shape' in which they are defined
print(cr.length)
print(cr.breadth)
1) What is Encapsulation in Python?
Encapsulation in Python is the process of wrapping up variables and methods into
a single entity.
In programming, a class is an example that wraps all the variables and methods
defined inside it.
2) How can we achieve Encapsulation in Python?
In Python, Encapsulation can be achieved using Private and Protected Access Members.
3) How can we define a variable as Private?
In Python, Private variables are preceded by using two underscores.
4) How can we define a variable as Protected?
In Python, Protected variables are preceded by using a single underscore.
Comments
Post a Comment