StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover Encapsulation
Download
  1. Python
  2. Pyhton MCA (Machine Learning using Python)
  3. Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP
Types of Inheritance : Abstraction
Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP

Encapsulation is a fundamental principle in Object-Oriented Programming (OOP) that involves bundling the data (attributes) and the methods (functions) that operate on that data into a single unit, or class. The primary goal of encapsulation is to practice information hiding, which means restricting direct access to an object's internal state and only exposing a controlled, public interface.

This prevents the data from being accidentally or purposefully modified in unintended ways, making the code more secure, robust, and easier to maintain.

1. Public, Protected, and Private Attributes (Access Modifiers)

Python doesn't have strict public, private, or protected keywords like other languages (e.g., Java or C++). Instead, it uses a naming convention with underscores as a signal to other developers.

a) Public Attributes

Attributes defined without a leading underscore are considered public. They are meant to be accessed and modified directly from outside the class.

  • Use Case: For data that is safe to be read and changed by anyone.

Python

# --- Public Attribute Example ---

class Car:

    def __init__(self, color):

        # 'color' is a public attribute.

        self.color = color

 

my_car = Car("Red")

# You can access and modify it directly.

print(f"The car's color is: {my_car.color}")

my_car.color = "Blue"

print(f"The car's new color is: {my_car.color}")

b) Protected Attributes (by convention)

An attribute with a single leading underscore (e.g., _name) is considered protected. This is a convention that tells other developers, "You shouldn't touch this attribute directly from outside the class, but it's okay for subclasses to use it."

  • Use Case: For internal attributes that are part of the class's implementation but might be needed by child classes that inherit from it.

Python

# --- Protected Attribute Example ---

class Person:

    def __init__(self, name):

        # '_name' is a protected attribute.

        self._name = name

 

# While you *can* still access it, the underscore signals that you shouldn't.

person = Person("Rohit")

print(f"Protected name: {person._name}")

c) Private Attributes (Name Mangling)

An attribute with two leading underscores (e.g., __balance) is considered private. Python performs a process called name mangling on these attributes, which makes them very difficult to access from outside the class.

  • Use Case: For critical data that must be protected from direct external modification. Access should only be granted through controlled methods (getters and setters).

Python

# --- Private Attribute Example ---

class BankAccount:

    def __init__(self, initial_balance):

        # '__balance' is a private attribute.

        self.__balance = initial_balance

 

account = BankAccount(1000)

# The following line would cause an AttributeError because the name has been mangled.

# print(account.__balance)

 

# You can still access it if you know the mangled name, but this is strongly discouraged.

print(f"Accessing the mangled name: {account._BankAccount__balance}")


2. Getters and Setters (Controlling Access)

The main way to practice encapsulation is to make your attributes private and provide public methods to interact with them.

  • Getter Method: A method that retrieves the value of a private attribute.

  • Setter Method: A method that modifies the value of a private attribute, often including validation logic.

  • Use Case: This is the core of encapsulation. It allows you to protect your data. For a BankAccount, you don't want anyone to be able to set the balance to a negative number. A setter method can enforce this rule.

Python

# --- Getters and Setters Example ---

class BankAccount:

    def __init__(self, initial_balance):

        # The balance is private.

        self.__balance = initial_balance

 

    # This is a "getter" method.

    def get_balance(self):

        """Returns the current account balance."""

        return self.__balance

 

    # This is a "setter" method with validation.

    def deposit(self, amount):

        """Deposits a positive amount into the account."""

        if amount > 0:

            self.__balance += amount

            print(f"Deposited ${amount}. New balance: ${self.__balance}")

        else:

            print("Error: Deposit amount must be positive.")

 

    def withdraw(self, amount):

        """Withdraws an amount if funds are sufficient."""

        if 0 < amount <= self.__balance:

            self.__balance -= amount

            print(f"Withdrew ${amount}. New balance: ${self.__balance}")

        else:

            print("Error: Invalid withdrawal amount or insufficient funds.")

 

# Create an account.

account = BankAccount(1000)

 

# You can't access the balance directly.

# print(account.__balance) # This would fail.

 

# You must use the controlled methods.

print(f"Initial balance: ${account.get_balance()}")

account.deposit(500)

account.withdraw(200)

account.deposit(-50) # This will be rejected by the setter logic.

account.withdraw(2000) # This will be rejected.

print(f"Final balance: ${account.get_balance()}")

 

Types of Inheritance Abstraction
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website