24. Problem to show encapsulation in Python

In this Python oops program, we will create a class to show encapsulation in Python. This example showcases the concept of private variables and methods in Python classes. 

Encapsulation in Python

Steps to solve the program
  1. The code defines a class named MyClass with a private instance variable __private_var and a private method __private_method.
  2. The double underscores before the variable and method names indicate that they are intended to be private, meaning they are intended to be used within the class only and not accessed directly from outside the class.
  3. An instance of the MyClass class is created and assigned to the variable obj.
  4. The public_method of the obj object is called. This method is a public method, which means it can be accessed from outside the class.
  5. Inside the public_method, the private method __private_method is called using self.__private_method().
  6. The private method __private_method prints “Private method” when called.
				
					class MyClass:
    def __init__(self):
        self.__private_var = 10
    
    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()
				
			

Output:

				
					Public method
Private method
				
			

Related Articles

Set Instance variable data with setattr and getattr methods.

Create a Python class called Rectangle with attributes length and width.

Leave a Comment