Menu Close

Mastering Data Hiding in Python

Data Hiding in Python

In this article, We are going to learn the most important concept of object-oriented programming called Data hiding. Data Hiding in Python is also known as encapsulation. To understand this concept you should have basic knowledge of Python programming. You can check out our Python tutorial to brush up your Python knowledge.

The main purpose of the data hiding in Python is to restrict direct access to the internal attributes and methods of a class.

Before learning Data hiding in Python You should have basic knowledge of Public, Private, and Protected specifiers in Python. You can learn from the Python access modifiers tutorial.

What is Data Hiding in Python?

Data Hiding in Python is one of the most important features. Data hiding in Python allows us to prevent the access of methods and attributes of a class directly. By default all the members of the class access outside of the class but sometimes we want to prevent them, Then we can use data-hiding concepts. We can prevent this by making private and protected data members.

Why Is Data Hiding Important?

The primary goal of data hiding is to protect the internal state of an object and ensure that should be manipulated in a controlled manner. The benefits of data hiding include:

  • Preventing Accidental Modification: By restricting access to internal data, you reduce the risk of external code accidentally modifying an object’s state.
  • Improving Maintainability: When the internal workings of a class are hidden, the implementation can be changed without affecting the external code that uses the class.
  • Security and Integrity: It helps maintain the integrity of the data and ensures that only approved actions can modify the object’s state.

Data Hiding in Python: Public, Protected, and Private Attributes

In Python, class members which means methods and attributes are classified into three categories Public, Private, and Protected. Let’s see all of these one by one.

Public Attributes and Methods

The members (Methods and Attributes) of the class are defined as public by default in Python and are easily accessible from any part of the program but within a program.

class Person:

    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

    def show_name(self):
        full_name = f"{self.first_name} {self.last_name}"
        return full_name


p1 = Person("Programming", "Funda")
print(p1.first_name)
full_name = p1.show_name()
print(full_name)

Output

Programming
Programming Funda

In the above code first_name, last_name attributes, and show_name() method are the public members.

Note:- If you will try to access p1.first_name then you can easily get it because first_name is the public atribite and it can be access inside and outside of the class.

Private Attributes and Methods

Private attributes and methods of the class can be accessed by the only class itself even not its child classes. To make attributes and methods private in Python, you need to use double underscore as a prefix in the attributes and methods.

This triggers name mangling which is a mechanism where the interpreter changes the attribute name to make it more difficult to access from outside the class.

To create private data members inside the class, we have to use a double underscore (__) before the data member ( Attributes and Methods).

class Person:

    def __init__(self, first_name, last_name):
        self.__first_name = first_name
        self.__last_name = last_name

    def __full_name(self):
        full_name = f"{self.__first_name} {self.__last_name}"
        return full_name

    def get_full_name(self):
        return self.__full_name()




p1 = Person("Programming", "Funda")
# p1.__first_name  # This line will raise an error

full_name = p1.get_full_name()
print(full_name)

In the above code, __first_name, __last_name and __full_name() are the private data member where __first_name and __last_name are attributes and __full_name() is the method.

Note:- If you will try to access p1.__first_name then you will get an error because __first_name is the protected atribite and it cannot be access outside of the class.

Protected Attributes and Methods

The members (Attributes and Methods ) of a class declared as protected are accessible outside of the class, within the class as well as its subclass. To create protected data inside the class, You need to use a single underscore (_) as a prefix before the data member.

The single underscore is just a naming convention that indicates to the developers, that attributes or methods are created for within and its child classes use.

To create a protected data member inside the class, we use a single underscore (_) before the data member.

class Car:

    def __init__(self, company_name):
        self._company_name = company_name

    def _show_company_name(self):
        return self._company_name


class Model(Car):

    def __init__(self, company_name, model_name):
        self.company_name = company_name
        self.model_name = model_name
        super().__init__(company_name)

    def show_details(self):
        print(f"Model name is {self.model_name}")
        print(f"Company name is {self._show_company_name()}")



m1 = Model("Ford", "Mustang")
m1.show_details()

Output


Model name is Mustang
Company name is Ford

As you can see in the above code _company_name and _show_company_name are the protected data members inside the Car class which are being accessed by its cub class called Model. Infect _company_name attribute and _show_company_name() method can be accessed outside of the class.

Let’s see when should we use Public, Private, and Protected data members.

When should we use Public, Private, and Protected

Choosing between public, protected, and private attributes or methods depends on the level of access control and encapsulation you want to enforce in your class design. Here’s a breakdown of when to use each:

Public Attributes and Methods

  • Default choice: Use public attributes and methods when you want them to be accessible from anywhere—both inside and outside the class.
  • No restrictions on access: If there is no need for encapsulation or controlled access, public attributes will be the best choice.

Protected Attributes and Methods

  • Subclass access: Use protected attributes when they should be accessible within the class itself and by subclasses, but discourage external access.
  • Encapsulation: If you want to encapsulate data and logic while still allowing subclasses to extend functionality without making everything public.
  • Controlled usage: The underscore (_) indicates that while access is possible, it should be treated with care, and is typically only for internal logic.

Private Attributes and Methods

  • Strict encapsulation: Use private attributes when you want to ensure that an attribute or method must be completely hidden from external access or subclass access.
  • Sensitive data: If the integrity of certain data or functionality is critical and should not be modified or accessed directly.
  • Prevent accidental changes: When you want to prevent developers from accidentally tampering with the internal workings of a class.

Read Also:

Conclusion

In this Data Hiding in Python article, We have seen all about Python data hiding with examples and use cases. This is the best way to constrain the access of the attributes and methods of the Python class. Make sure know about the Python OOPs concepts to understand the data hiding in Python.

If you found this article helpful, Please share and keep visiting for further Python tutorials.

For More Information:- Click Here

This article was written and verified by Vishvajit Rao.

Ultimate Python List Tutorial: Mastering Data Structures
25+ Python While Loop Questions and Answers

Related Posts