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
- The code defines a class named MyClass with a private instance variable __private_var and a private method __private_method.
- 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.
- An instance of the MyClass class is created and assigned to the variable obj.
- 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.
- Inside the public_method, the private method __private_method is called using self.__private_method().
- 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
Create a Python class called Rectangle with attributes length and width.
Create a Python class called Circle with attributes radius.
Create a Python class called Person with attributes name and age.
Create a Python class called Student that inherits from the Person class.
Create a Python class called Cat that inherits from the Animal class.
Create a Python class called BankAccount with attributes account_number and balance.