Which of the following is an example of encapsulation in Python?

Which of the following is an example of encapsulation in Python?

a) Using private variables and methods within a class
b) Creating multiple classes in a module
c) Inheriting from a base class
d) Overloading methods

Answer:

a) Using private variables and methods within a class

Explanation:

Encapsulation in Python refers to the practice of bundling data (attributes) and methods that operate on the data into a single unit, or class, and restricting access to some of the object’s components. This is achieved by using private variables and methods, which are indicated by a leading underscore (_) or double underscore (__).

class Account:
def __init__(self, owner, balance):
    self.owner = owner
    self.__balance = balance  # Private variable

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

def get_balance(self):
    return self.__balance

# Accessing private attribute
account = Account("Alice", 1000)
print(account.get_balance())  # Output: 1000

In this example, the __balance attribute is encapsulated within the Account class, making it inaccessible from outside the class. The class provides methods like get_balance() to interact with the private attribute in a controlled manner.

Encapsulation helps protect the internal state of an object and ensures that it can only be modified through well-defined methods, improving code reliability and security.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top