• Articles

What is Encapsulation in Python with Examples?

What is Encapsulation in Python with Examples?

In this blog, we will explore the core concepts of encapsulation, how it improves code modularity and reusability, and demonstrate its practical implementation with examples. By the end, you will understand encapsulation in Python programming and how to use it for reliable applications.

Table of Contents

Unlock the power of Object-Oriented Programming in Python with our OOPS tutorial on Intellipaat! Dive into encapsulation and elevate your Python skills now.

Video Thumbnail

What is Encapsulation in Python?

Encapsulation in Python is the process of bundling both data and methods that work with that data into a single unit. This means that the data is hidden from the outside world and can only be accessed through the methods of the class. This helps to prevent accidental changes or misuse of the data.

Certainly! Let’s consider a simple example of encapsulation.

Imagine you have a “LibraryBook” class. Inside this class, there’s an attribute called `_isBorrowed`, which indicates whether the book is currently borrowed or available. To hide this information from external interference, you don’t directly access `_isBorrowed`. Instead, you use two methods: `borrowBook()` and `returnBook()`. 

  •  `borrowBook()` sets `_isBorrowed` to ‘True‘ when someone borrows the book.
  •  `returnBook()` sets `_isBorrowed` to ‘False‘ when the book is returned.

By encapsulating `_isBorrowed` in this way, you can protect it from being unintentionally changed or manipulated. It’s like having a librarian who manages the book’s status – readers can only borrow or return the book through the librarian, ensuring that the book’s availability is controlled and not directly tampered with.

Master Python, the language of innovation and automation, with our Python course that unlocks endless possibilities in coding.

Why Do We Need Encapsulation in Python?

Python does not have direct access modifiers like public, private, and protected. Yet, it does have a convention for naming variables and methods to indicate their accessibility. Variables and methods that start with a single underscore (_) are considered private and should not be accessed from outside the class. Variables and methods that start with a double underscore (__) are considered special and have special meaning to Python.

Encapsulation in Python

Examples

In this example, we create a Car class by defining car attributes such as make and model as an instance variable and implementing behavior using display_info() and start_engine() instance methods.

class Car:
    # constructor
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
    # method
    # to display car's info
    def display_info(self):
        # accessing public data member
        print(f"Car Info: {self.year} {self.make} {self.model}")
    # method
    def start_engine(self):
        print(f"The {self.make} {self.model}'s engine is running.")
# Creating an object of the Car class
my_car = Car("Toyota", "Camry", 2022)
# Displaying car information
my_car.display_info()
# Starting the car's engine
my_car.start_engine()

Output

encapsulation in python output

In this code:

  • The “Car” class has attributes for the car’s make, model, and year, and methods to display information and start the engine.
  • An instance of the “Car” class, my_car, is created with specific details.
  • The display_info method is called to show information about the car.
  • The start_engine method is called to start the car’s engine.

Know about Python developer roles and responsibilities to begin a career as a Python developer.

Get 100% Hike!

Master Most in Demand Skills Now!

Access Modifiers in Python

Various object-oriented programming languages like C++, Java, and Python have access modifiers that restrict variables and methods. These modifiers come in three main types: Public, Protected, and Private. Python uses the underscore (_) to set these access levels for data and functions inside a class. 

  • Public Access Modifier: Accessible anywhere from outside class.
  • Private Access Modifier: Accessible within the class
  • Protected Access Modifier: Accessible within the class and its sub-classes.

Access modifiers are like security guards for your class. It keeps your data safe from being used or changed by unauthorized access and prevents it from being exploited.

Data Hiding Using Encapsulation

Elevate your career with our free Python course and earn a valuable certification to showcase your expertise!

Public Access Modifier

Public Access Modifier in Python is used to indicate that a variable or method is accessible from anywhere in the program. This is the default access modifier for all variables and methods in Python.

To mark a variable or method as public, you simply need to leave the name of the variable or method as it is. For example, the following code defines a public variable and a public method:

class Person:
    name = "Akash"
    def greet(self):
        print("Hello, my name is Akash!")

The name variable and the greet() method are both public, which means that they can be accessed from anywhere in the program. For example, the following code shows how to access the name variable and call the greet() method outside the Person class:

person = Person()
print(person.name)
person.greet()

Output: 

public access modifier

Discover the Python tutorial that will ignite your coding journey and empower you to create, automate, and innovate.

Private Access Modifier

Private Access Modifier in Python is used to indicate that a variable or method is only accessible from within the class in which it is defined. This is the most restrictive access modifier in Python, and it is typically used to protect sensitive data and behavior.

To mark a variable or method as private, you simply need to prefix the name of the variable or method with a double underscore (__). For example, the following code defines a private variable and a private method:

class Person:
    __name = "Akash"
    def __greet(self):
        print("Hello, my name is Akash!")

The __name variable and the __greet() method are both private, which means that they can only be accessed from within the Person class. For example, the following code will not work because it is trying to access the private __name variable from outside of the Person class:

person = Person()
print(person.__name)

Output

Private Access Modifier

Want to pursue a career in Python Domain? Master Python developer skills and start your career.

Protected Access Modifier

Protected Access Modifier in Python is used to indicate that a variable or method is accessible from within the class and from its subclasses. This is a useful way to encapsulate data and behavior while still allowing subclasses to access and extend it.

To mark a variable or method as protected, you simply need to prefix the name of the variable or method with a single underscore (_). For example, the following code defines a protected variable and a protected method:

class Person:
    _name = "Akash"
    def _greet(self):
        print("Hello, my name is Akash!")

The name variable and the greet() method are both protected, which means that they can be accessed from within the Person class and from its subclasses. For example, the following code shows how to access the name variable and call the greet() method from a subclass of the Person class:

class Student(Person):
    def introduce(self):
        print(f"I am a student named {self._name}.")
student = Student()
student.introduce()

Output: 

Protected Access Modifier

Preparing for Job Interview? Refer to Python Interview Questions to excel in your Interviews!

Getters and Setters in Python

Getters and setters in Python are methods that allow you to access and modify private attributes of a class. They are a good way to encapsulate data and behavior and to control how private attributes are accessed and modified.

To create a getter method, you simply need to define a public method that returns the value of a private attribute. For example, the following code defines a private attribute name and a public getter method get_name():
class Person:
    def __init__(self, name):
        self._name = name
    def get_name(self):
        return self._name
# Create a new Person object
person = Person("Akash")
# Get the person's name
name = person.get_name()
# Print the person's name
print(name)

Output

Getters in Python

To create a setter method, you simply need to define a public method that takes a value as input and sets the value of a private attribute. For example, the below code explains a private attribute name and a public setter method set_name():

class Person:
    def __init__(self, name):
        self.__name = name
    def set_name(self, new_name):
        self.__name = new_name
    def get_name(self):
        return self.__name
# Create a new Person object
person = Person("Akash")
# Set the person's name
person.set_name("New Akash")
# Get the person's name
name = person.get_name()
# Print the person's name
print(name)

Output

Setters in Python

Getter and setter methods are a good way to access and modify private attributes in Python. They allow you to control how private attributes are accessed and modified, and they can help to make your code more secure and maintainable.

Know about Python developer roles and responsibilities to begin a career as a Python developer.

Advantages of Encapsulation

The advantages of encapsulation in Python include the following:

  • Data Hiding: It safeguards the data within an object, preventing unauthorized changes from the outside.
  • Simplicity: Encapsulation simplifies code by hiding the nitty-gritty details of how things work. This makes the code more understandable and easier to maintain.
  • Code Reusability: It helps code be reused by giving a clear public interface for a class. This lets other parts of the program use it well.
  • Improved Maintainability: With encapsulation, you can modify the inner workings of a class without impacting the rest of the program. This makes maintaining the code smoother.
  • Better Control Over Class Properties: Encapsulation restricts variables and methods to the class where they are defined, reducing the risk of naming conflicts and providing better control over class properties.

Conclusion

In simple terms, encapsulation in Python is like putting your code in a protective bubble. It helps keep your code organized and safe. By hiding some parts of your code and controlling how others can use it, you can prevent problems and make your programs easier to understand and work on. So, when you use encapsulation, you’re like a code wizard, ensuring your spells (code) work well and without causing unexpected troubles. Keep using encapsulation to make your Python projects more reliable and easier to handle!

Course Schedule

Name Date Details
Python Course 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch

Full Stack Development