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.

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.

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 .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.

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 an engine of car.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.

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

Public Access Modifier: Carry out any where from outside class.

Private Access Modifier: Accessible within the class

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 aimed to exploit it.

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.

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:

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 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: 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:

Output

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 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:

Private Access Modifier in Python is an indicator that this particular variable or method can be only used within the class it is defined in. This is considered to be the least accessible type in Python and it is commonly used to safeguard data and action.

The identifier is easily defined by simply preceding the name of the variable or the method with double underscores (__). 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 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: 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

Output

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():

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

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.
  6. Data Hiding: It safeguards the data within an object, preventing unauthorized changes from the outside.
  7. Simplicity: Encapsulation simplifies code by hiding the nitty-gritty details of how things work. This makes the code more understandable and easier to maintain.
  8. 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.
  9. 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.
  10. 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

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!

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! 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 14th Jan 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 Development