In this Python oops program, we will create a class with data hiding i.e. encapsulation in Python. This Python class example demonstrates data hiding or encapsulation in Python with name mangling with the help of the below-given steps.
Encapsulation in Python
Steps to solve the program
- The MyClass has an __init__ method that initializes an instance variable __private_var with a value of 25. The double underscore prefix before the variable name makes it a private variable.
- The class also has a __private_method method, which is a private method indicated by the double underscore prefix. This method simply prints “Private method”.
- There is a public_method defined in the class, which is a public method and can be accessed outside the class. It prints “Public method” and calls the private method __private_method().
- An object obj of the MyClass is created.
- The public_method() is called on the obj object, which prints “Public method” and calls the private method __private_method().
- We try to access the private variable __private_var using print(obj._MyClass__private_var). Python uses name mangling to modify the name of the private variable by adding _MyClass prefix to the variable name. This allows limited access to the private variable outside the class.
- The value of the private variable is printed, which is 25.
class MyClass:
def __init__(self):
self.__private_var = 25
def __private_method(self):
print("Private method")
def public_method(self):
print("Public method")
self.__private_method()
# Create an object of the class
obj = MyClass()
# Access public method and variable
obj.public_method()
print(obj._MyClass__private_var) # Access private variable (Name Mangling)
Output:
Public method
Private method
25
Related Articles
Python Class Structure for School Management System.
Write a Python Class Structure for Employee Management Application.
Write a Python Class with @property decorator.
Write a Python Class structure with module-level Import.
Create 5 different Python Classes and access them via a single class object.
Create 5 Python classes and set up multilevel inheritance among all the classes.