- Encapsulation in Python
- Table of contents
- What is Encapsulation in Python?
- Access Modifiers in Python
- Public Member
- Private Member
- Public method to access private members
- Name Mangling to access private members
- Protected Member
- Getters and Setters in Python
- Advantages of Encapsulation
- About Vishal
- Related Tutorial Topics:
- Python Exercises and Quizzes
- Encapsulation in Python
- Protected members
Encapsulation in Python
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP), including abstraction, inheritance, and polymorphism. This lesson will cover what encapsulation is and how to implement it in Python.
After reading this article, you will learn:
- Encapsulation in Python
- Need for Encapsulation
- Data Hiding using public, protected, and private members
- Data Hiding vs. Encapsulation
- Getter and Setter Methods
- Benefits of Encapsulation
Table of contents
What is Encapsulation in Python?
Encapsulation in Python describes the concept of bundling data and methods within a single unit. So, for example, when you create a class, it means you are implementing encapsulation. A class is an example of encapsulation as it binds all the data members (instance variables) and methods into a single unit.
In this example, we create an Employee class by defining employee attributes such as name and salary as an instance variable and implementing behavior using work() and show() instance methods.
class Employee: # constructor def __init__(self, name, salary, project): # data members self.name = name self.salary = salary self.project = project # method # to display employee's details def show(self): # accessing public data member print("Name: ", self.name, 'Salary:', self.salary) # method def work(self): print(self.name, 'is working on', self.project) # creating object of a class emp = Employee('Jessa', 8000, 'NLP') # calling public method of the class emp.show() emp.work()
Name: Jessa Salary: 8000 Jessa is working on NLP
Using encapsulation, we can hide an object’s internal representation from the outside. This is called information hiding.
Also, encapsulation allows us to restrict accessing variables and methods directly and prevent accidental data modification by creating private data members and methods within a class.
Encapsulation is a way to can restrict access to methods and variables from outside of class. Whenever we are working with the class and dealing with sensitive data, providing access to all variables used within the class is not a good choice.
For example, Suppose you have an attribute that is not visible from the outside of an object and bundle it with methods that provide read or write access. In that case, you can hide specific information and control access to the object’s internal state. Encapsulation offers a way for us to access the required variable without providing the program full-fledged access to all variables of a class. This mechanism is used to protect the data of an object from other objects.
Access Modifiers in Python
Encapsulation can be achieved by declaring the data members and methods of a class either as private or protected. But In Python, we don’t have direct access modifiers like public, private, and protected. We can achieve this by using single underscore and double underscores.
Access modifiers limit access to the variables and methods of a class. Python provides three types of access modifiers private, public, and protected.
- Public Member: Accessible anywhere from otside oclass.
- Private Member: Accessible within the class
- Protected Member: Accessible within the class and its sub-classes
Public Member
Public data members are accessible within and outside of a class. All member variables of the class are by default public.
class Employee: # constructor def __init__(self, name, salary): # public data members self.name = name self.salary = salary # public instance methods def show(self): # accessing public data member print("Name: ", self.name, 'Salary:', self.salary) # creating object of a class emp = Employee('Jessa', 10000) # accessing public data members print("Name: ", emp.name, 'Salary:', emp.salary) # calling public method of the class emp.show()
Name: Jessa Salary: 10000 Name: Jessa Salary: 10000
Private Member
We can protect variables in the class by marking them private. To define a private variable add two underscores as a prefix at the start of a variable name.
Private members are accessible only within the class, and we can’t access them directly from the class objects.
class Employee: # constructor def __init__(self, name, salary): # public data member self.name = name # private member self.__salary = salary # creating object of a class emp = Employee('Jessa', 10000) # accessing private data members print('Salary:', emp.__salary)
AttributeError: 'Employee' object has no attribute '__salary'
In the above example, the salary is a private variable. As you know, we can’t access the private variable from the outside of that class.
We can access private members from outside of a class using the following two approaches
Public method to access private members
Example: Access Private member outside of a class using an instance method
class Employee: # constructor def __init__(self, name, salary): # public data member self.name = name # private member self.__salary = salary # public instance methods def show(self): # private members are accessible from a class print("Name: ", self.name, 'Salary:', self.__salary) # creating object of a class emp = Employee('Jessa', 10000) # calling public method of the class emp.show()
Name Mangling to access private members
We can directly access private and protected variables from outside of a class through name mangling. The name mangling is created on an identifier by adding two leading underscores and one trailing underscore, like this _classname__dataMember , where classname is the current class, and data member is the private variable name.
Example: Access private member
class Employee: # constructor def __init__(self, name, salary): # public data member self.name = name # private member self.__salary = salary # creating object of a class emp = Employee('Jessa', 10000) print('Name:', emp.name) # direct access to private member using name mangling print('Salary:', emp._Employee__salary)
Protected Member
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 _ .
Protected data members are used when you implement inheritance and want to allow data members access to only child classes.
Example: Proctecd member in inheritance.
# base class class Company: def __init__(self): # Protected member self._project = "NLP" # child class class Employee(Company): def __init__(self, name): self.name = name Company.__init__(self) def show(self): print("Employee name :", self.name) # Accessing protected member in child class print("Working on project :", self._project) c = Employee("Jessa") c.show() # Direct access protected data member print('Project:', c._project)
Employee name : Jessa Working on project : NLP Project: NLP
Getters and Setters in Python
To implement proper encapsulation in Python, we need to use setters and getters. The primary purpose of using getters and setters in object-oriented programs is to ensure data encapsulation. Use the getter method to access data members and the setter methods to modify the data members.
In Python, private variables are not hidden fields like in other programming languages. The getters and setters methods are often used when:
- When we want to avoid direct access to private variables
- To add validation logic for setting a value
class Student: def __init__(self, name, age): # private member self.name = name self.__age = age # getter method def get_age(self): return self.__age # setter method def set_age(self, age): self.__age = age stud = Student('Jessa', 14) # retrieving age using getter print('Name:', stud.name, stud.get_age()) # changing age using setter stud.set_age(16) # retrieving age using getter print('Name:', stud.name, stud.get_age())
Name: Jessa 14 Name: Jessa 16
Let’s take another example that shows how to use encapsulation to implement information hiding and apply additional validation before changing the values of your object attributes (data member).
Example: Information Hiding and conditional logic for setting an object attributes
class Student: def __init__(self, name, roll_no, age): # private member self.name = name # private members to restrict access # avoid direct data modification self.__roll_no = roll_no self.__age = age def show(self): print('Student Details:', self.name, self.__roll_no) # getter methods def get_roll_no(self): return self.__roll_no # setter method to modify data member # condition to allow data modification with rules def set_roll_no(self, number): if number > 50: print('Invalid roll no. Please set correct roll number') else: self.__roll_no = number jessa = Student('Jessa', 10, 15) # before Modify jessa.show() # changing roll number using setter jessa.set_roll_no(120) jessa.set_roll_no(25) jessa.show()
Student Details: Jessa 10 Invalid roll no. Please set correct roll number Student Details: Jessa 25
Advantages of Encapsulation
- Security: The main advantage of using encapsulation is the security of the data. Encapsulation protects an object from unauthorized access. It allows private and protected access levels to prevent accidental data modification.
- Data Hiding: The user would not be knowing what is going on behind the scene. They would only be knowing that to modify a data member, call the setter method. To read a data member, call the getter method. What these setter and getter methods are doing is hidden from them.
- Simplicity: It simplifies the maintenance of the application by keeping classes separated and preventing them from tightly coupling with each other.
- Aesthetics: Bundling data and methods within a class makes code more readable and maintainable
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
- 15+ Topic-specific Exercises and Quizzes
- Each Exercise contains 10 questions
- Each Quiz contains 12-15 MCQ
Encapsulation in Python
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. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data. To prevent accidental change, an object’s variable can only be changed by an object’s method. Those types of variables are known as private variables.
A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc. The goal of information hiding is to ensure that an object’s state is always valid by controlling access to attributes that are hidden from the outside world.
Consider a real-life example of encapsulation, in a company, there are different sections like the accounts section, finance section, sales section etc. The finance section handles all the financial transactions and keeps records of all the data related to finance. Similarly, the sales section handles all the sales-related activities and keeps records of all the sales. Now there may arise a situation when due to some reason an official from the finance section needs all the data about sales in a particular month. In this case, he is not allowed to directly access the data of the sales section. He will first have to contact some other officer in the sales section and then request him to give the particular data. This is what encapsulation is. Here the data of the sales section and the employees that can manipulate them are wrapped under a single name “sales section”. Using encapsulation also hides the data. In this example, the data of the sections like sales, finance, or accounts are hidden from any other section.
Protected members
Protected members (in C++ and JAVA) are those members of the class that cannot be accessed outside the class but can be accessed from within the class and its subclasses. To accomplish this in Python, just follow the convention by prefixing the name of the member by a single underscore “_”.
Although the protected variable can be accessed out of the class as well as in the derived class (modified too in derived class), it is customary(convention not a rule) to not access the protected out the class body.
Note: The __init__ method is a constructor and runs as soon as an object of a class is instantiated.