The process of wrapping up variables and methods into a single entity is known as Encapsulation. It is one of the underlying concepts in object-oriented programming (OOP). It acts as a protective shield that puts restrictions on accessing variables and methods directly, and can prevent accidental or unauthorized modification of data. Encapsulation also makes objects into more self-sufficient, independently functioning pieces.
Access modifiers limit access to the variables and functions of a class. Python uses three types of access modifiers; they are - private, public and protected.
Public members are accessible anywhere from the class. All the member variables of the class are by default public.
# program to illustrate public access modifier in a classclass edpresso:# constructordef __init__(self, name, project):self.name = name;self.project = project;def displayProject(self):# accessing public data memberprint("Project: ", self.project)# creating object of the classedp = edpresso("TeamPhoenix", 1);# accessing public data memberprint("Name: ", edp.name)# calling public member function of the classedp.displayProject()
In class edpresso
, the variable name
and project
are public. These data members can be accessed anywhere in the program.
Protected members are accessible within the class and also available to its sub-classes. To define a protected member, prefix the member name with a single underscore “_”.
# program to illustrate protected access modifier in a classclass edpresso:def __init__(self, name, project):self._name = nameself._project = project# creating object of the classedp = edpresso("TeamPhoenix", 2)# direct access of protected memberprint("Name:",edp._name)print("project:",edp._project)
The variable name
and project
of class edpresso
are protected; hence, it is accessed as _name
, and _project
respectively.
Private members are accessible within the class. To define a private member, prefix the member name with a double underscore “__”.
# program to illustrate private access modifier in a classclass edpresso:def __init__(self, name, project):# public variableself.name = name# private variableself.__project = project# creating an instance of the class Sampleedp = edpresso('TeamPhoenix', 3)# accessing public variable nameprint("Name:",edp.name)# accessing private variable __project using# _Edpresso__project nameprint("Project:",edp._edpresso__project)
In class edpresso
, __project
is a private variable; hence, it is accessed by creating an instance.
Thanks for reading!
Happy Coding.