Encapsulation with Access Modifiers in Python


Encapsulation in Python

Encapsulation in Python

Definition

Encapsulation is the concept of restricting direct access to an object’s data and methods to protect data integrity.

Access Modifiers

  • Private: Accessible only within the class.
  • Protected: Accessible within the class and its subclasses.
  • Public: Accessible from anywhere.

Encapsulation without Access Modifiers

Program:

class Product:
    def __init__(self, name, price):
        # Public attributes (default)
        self.name = name
        self.price = price

    def display_product(self):
        # Method to display product details
        print(f"Product: {self.name}, Price: {self.price}")

p1 = Product("Laptop", 75000)  # Create object
p1.display_product()  # Output: Product: Laptop, Price: 75000
    

Encapsulation with Access Modifiers

Private

Definition: Variables or methods prefixed with __ are private and not accessible directly outside the class.

Program:

class Bank:
    def __init__(self):
        self.__bank_name = "State Bank of India"  # Private attribute

    def get_bank_name(self):
        # Access private attribute within the class
        print(self.__bank_name)

b1 = Bank()  # Create object
b1.get_bank_name()  # Output: State Bank of India
# print(b1.__bank_name)  # Error: Cannot access private attribute directly
    

Protected

Definition: Variables or methods prefixed with _ are protected and can be accessed within the class or its subclasses.

Program:

class University:
    def __init__(self):
        self._university_name = "Anna University"  # Protected attribute

class Department(University):
    def display_university_name(self):
        # Access protected attribute in the subclass
        print(f"Department belongs to: {self._university_name}")

d1 = Department()  # Create subclass object
d1.display_university_name()  # Output: Department belongs to: Anna University
    

Public

Definition: Variables or methods without any prefix are public and accessible from anywhere.

Program:

class Library:
    def __init__(self):
        self.library_name = "Central Library"  # Public attribute

class Section(Library):
    pass  # Inherits everything from Library

s1 = Section()  # Create subclass object
print(s1.library_name)  # Output: Central Library
    

Post a Comment

0 Comments