Professional Documents
Culture Documents
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It describes the idea of wrapping data and the
methods that work on data within one unit.
A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc.
Access Modifiers
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
Public members are accessible anywhere from the class. All the member variables of the class are by default public.
class Student:
# constructor
def __init__(self, name, project):
self.name = name;
self.project = project;
def displayProject(self):
# accessing public data member
print("Project: ", self.project)
Name: Philip
Project: 1
In class Student, the variable name and project are public. These data members can be accessed anywhere in the program.
Protected members
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 “_”.
class Student:
def __init__(self, name, project):
self._name = name
self._project = project
Name: Philip
project: 2
The variable name and project of class Student are protected; hence, it is accessed as _name, and _project respectively.
Private members
Private members are accessible within the class. To define a private member, prefix the member name with a double underscore “__”.
class Student:
def __init__(self, name, project):
# private variable
self.__name = name
# private variable
self.__project = project
Name: Philip
Project: 3
In class Student, name and project are both private variables.Hence, they are accessed by including the name of the class.
Exercises
Write a python class named Bird with private attributes name
Create a class Vehicle with private attributes color and name. Create an object of the Vehicle class and access the private attribute color.
Write a Python class named Circle with an private instance attribute radius and two methods which will compute the area and the
perimeter of a circle.
Create a class Student with private attributes name. Define a setName method which will accept name from the user and also Define a
getName which will return the attribute name