w3resource

How does encapsulation provide data hiding in Python?

Python Encapsulation: Understanding data hiding mechanisms

In Python, encapsulation hides data through access modifiers and conventions. While Python doesn't enforce strict access control like some other programming languages, it offers mechanisms to achieve data hiding and controlled access to attributes and methods within a class.

Python's encapsulation provides data hiding in the following ways:

Access Modifiers:

Python uses naming conventions to indicate the visibility of attributes and methods. By convention, attributes and methods that start with a single underscore '_' are considered protected, while those that start with a double underscore '__' are considered private. This doesn't prevent direct access, but it signals other programmers that these members are intended for internal use.

Name Mangling:

Python performs name mangling for attributes that start with double underscores '__'. This means the attribute name gets modified by adding '_classname' in front of it. For example, if you have an attribute named '__value' in a class named "MyClass", it will be stored as '_MyClass__value' in the instance dictionary. This makes it difficult to accidentally override attributes in subclasses.

Conventions:

Developers follow conventions and not directly access protected or private members. The use of a single underscore '_' prefix serves as a gentle reminder that certain members are intended for internal use.

Example:

class Bank_Savings_Account:
    def __init__(self, balance):
        self._balance = balance  # Protected attribute

    def deposit(self, amount):
        self._balance += amount

    def withdraw(self, amount):
        if amount <= self._balance:
            self._balance -= amount
        else:
            print("Insufficient funds")

    def get_balance(self):
        return self._balance

# Usage
account = Bank_Savings_Account(1200)
account.deposit(800)
account.withdraw(900)
print(account.get_balance())  # Accessing the protected attribute
# The following is allowed but not recommended
print(account._balance)
account.withdraw(1500)
print(account.get_balance())  # Accessing the protected attribute
# The following is allowed but not recommended
print(account._balance)

In the example above-

The _balance attribute is intended for internal use, but it can still be accessed directly. Encapsulation relies on programmers adhering to conventions and not accessing protected or private attributes directly from outside the class. By using the convention, data is hidden and the intended use of attributes is communicated to other developers.



Follow us on Facebook and Twitter for latest update.