What is Encapsulation in Python with Examples?

What is Encapsulation in Python with Examples?

The main topics of this blog are encapsulation, how it increases the modularity and reusability of code, and how it can be done in practice. By the end of this part, you will understand encapsulation in Python programming and how to utilize it in real-world applications.

Table of Contents

What is Encapsulation in Python?

In Python, Encapsulation is the act of grouping the data type and methods that interact with it together. In other words, the data is concealed from the rest of the world and is only accessible through the class’s operations. This also avoids additional changes to the data or inappropriate manipulation of the data.

Certainly! Now let’s take a closer look at an example of encapsulation for newcomers.

Suppose you have a “LibraryBook” class. At the same time, this class contains the attribute `_isBorrowed`, which shows the state of the book, as well as borrowed or free. To prevent this information from being accessed and influenced by the outside world you do not directly make any changes to `_isBorrowed`. Instead, you use two methods: It contains two functions, namely `borrowBook()` and ‘returnBook().

  •  As its name suggests, `borrowBook()` is used when somebody borrows a book. It sets the `_isBorrowed` attribute to ‘True’.
  •  `returnBook()` function annotates `_isBorrowed` as ‘False’ when the book is being returned.

In this manner, you shield `_isBorrowed` from becoming modified or manipulated when this is not wanted. It’s like a librarian who controls books, and no one can change the status of a book themselves; for instance, borrow a book or return a book; they have to go through the librarian.

Why Do We Need Encapsulation in Python?

Encapsulation in Python

In Python, there are no direct access modifiers such as public, private, or protected. However, C has the convention of naming the variables and methods in order to specify their level of access. Items that start with the underscore (_) should not be accessed from outside this class; such variables and methods are private. Double underscore (__) means that variables and methods are special to Python and they have some special meaning.

Examples

In this example, we define an instance variable make and model of a car and then add behavior using our 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

Output

In this code:

  • The “Car” class described above has fields which are make, model, and year of the car and function that can show information and start the engine.
  • A sample of the “Car” class, my_car is instantiated with relevant hallmarks.
  • When it is required to display some information about the car, the display_info method is invoked.
  • The start_engine method is responsible for starting the engine of a car.

Access Modifiers in Python

Access Modifiers in Python

Some OOP languages like C++, Java, and Python have access modifiers that limit the variables and methods. These modifiers come in three main types: public, protected, and private. Python uses the underscore (_) sign in a class to indicate these different access levels of data and functions

1. Public Access Modifier: Carry out anywhere from outside the class.

2. Private Access Modifier: Accessible within the class

3. Protected Access Modifier: Available only in the class and its subclasses.

Access modifiers act like bouncers to your class, once they prevent certain objects that you do not want to have access to from getting in. It secures your data against usage or modification by an individual or program that aims to exploit it.

1. Public Access Modifier

Public Access Modifier in Python describes a certain variable or method that is visible for access from any place in Python. This is the simplest access level of variables and methods in a Python class and can be accessed from any other class.

The way to make it public is to leave the name of the variable or a method with no prefix at all. 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 variable and method greet() are public, which means you can access them anywhere in the whole program. Example: Refer to the following code to show how to access the variable name and call the greet() method outside the Person class:

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

Output:

Output

2. Private Access Modifier

A private access modifier in Python is an indicator that this variable or method is accessible within the class itself. As far as visibility goes, this type is the least accessible in Python, generally used for the protection of data and actions.

The identifier is simply established by preceding the variable or method name with double underscores (__). For example, the following code shows a private variable and private method:

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

The __name variable and the __greet() method both are private, meaning they can be accessed only from within the Person class. For instance, the following code will not work, as it tries to access the private __name variable from outside the Person class:

person = Person()
print(person.__name)

Output

Output

3. Protected Access Modifier

The Protected Access Modifier in Python shows that a variable or method can be accessed only by the class in question and any subclass. This is rather helpful when data and behavior have to be bundled together, but subclasses must be able to access and expand them.

In order to declare that a certain variable or method is protected, one only needs to underscore the name in the form _name. For example, the following code defines a protected variable and a protected method:

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:

Getters and Setters in Python

Getters and setters, in Python, are special methods that enable access to a class’s private characteristics. This simply means that they work well when used to hide data and behavior while also providing control over accessing and changing the values of private properties.

To implement a getter method, all one has to do is declare another public method whose role will be to retrieve the value of a private variable. 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

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

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.

Advantages of Encapsulation

The advantages of encapsulation in Python include the following:

  1. Data Hiding: It protects information within an object in order to avoid alterations by external forces.
  2. Simplicity: Encapsulation reduces complexity and removes most of the details that pertain to how that particular functionality or specific processes work out. This makes the program more comprehensible and thus easier to manipulate and modify as well.
  3. Code Reusability: It assists code in being reusable by providing a clear and public face of a class. It simply allows other areas of the program to use it properly.
  4. Improved Maintainability: Encapsulation therefore makes it possible to change the internal aspects of an object without affecting the other components of the program. This makes the work of maintaining the code less challenging.
  5. Better Control Over Class Properties: Encapsulation limits the access of variables and methods within the class where they are created to avoid naming clashes and increase the ability of the class to control its properties.

Conclusion

As put in simple terms encapsulation in Python is like placing your code in a bubble to protect it. It aids in the easy maintenance and also security of your code. When some portions of your code are not visible, and you manage the ways in which others can manipulate it or view it, issues and barriers can be mitigated, and working in programs becomes convenient. Well, when you practice encapsulation, you are a programmer magician; when you cast spells (code), you make sure they are well spelled out with no odd consequences. Continue using encapsulation in order to improve the reliability of your Python projects as well as make working with them more convenient! You can master these concepts by just enrolling in Intellipaat’s Python Programming Course and taking a leap into the new growing world of programming.

Our Python Courses Duration and Fees

Program Name
Start Date
Fees
Cohort starts on 15th Feb 2025
₹20,007

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

Full Stack Developer Course Banner