16. Problem to show encapsulation in python

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
  1. 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.
  2. 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”.
  3. 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().
  4. An object obj of the MyClass is created.
  5. The public_method() is called on the obj object, which prints “Public method” and calls the private method __private_method().
  6. 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.
  7. 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 Program with an Abstract method.

Python Class Structure for School Management System.

Leave a Comment