Python - Encapsulation

Why should I learn to solve Python: Encapsulation technical interview questions?

Learn and practise solving Python: Encapsulation technical interview questions and answers to enhance your skills for clearing technical interviews, HR interviews, campus interviews, and placement tests.

Where can I get technical Python: Encapsulation technical interview questions and answers with explanations?

IndiaBIX provides you with lots of fully solved Python: Encapsulation technical interview questions and answers with a short answer description. You can download Python: Encapsulation technical interview questions and answers as PDF files or e-books.

How do I answer Python: Encapsulation technical interview questions from various companies?

You can answer all kinds of Python: Encapsulation technical interview questions by practising the given exercises (short answer type). You can also find the frequently asked Python: Encapsulation technical interview questions with answers from various companies, such as TCS, Wipro, Infosys, CTS, IBM, etc.

1.
What is encapsulation in Python?

Encapsulation is one of the fundamental principles of object-oriented programming (OOP) that restricts access to some of an object's components, such as attributes or methods, and prevents the accidental modification of data. In Python, encapsulation is achieved using private and public access modifiers. In Python, a variable or method can be made private by prefixing it with a double underscore (__). This means that it cannot be accessed directly from outside the class. However, it can still be accessed within the class. Let's take a look at an example to demonstrate encapsulation in Python:

class EncapsulationExample:
    def __init__(self):
        self.__private_var = 10  # private variable

    def get_private_var(self):
        return self.__private_var

    def set_private_var(self, value):
        self.__private_var = value

# Creating an instance of the class
obj = EncapsulationExample()

# Accessing private variable using public methods
print(obj.get_private_var())  # Output: 10

obj.set_private_var(20)
print(obj.get_private_var())  # Output: 20

In this example, the variable __private_var is encapsulated within the class EncapsulationExample. The access to this variable is controlled through public methods get_private_var and set_private_var. This ensures that the variable is not directly accessible from outside the class, promoting encapsulation.

Output:

10
20

2.
Explain the concept of information hiding in encapsulation.

Information hiding is a key concept in encapsulation that refers to the practice of restricting the access to certain details of an object and revealing only what is necessary. This helps in preventing unintended interference and manipulation of the internal state of an object. In Python, information hiding is achieved through encapsulation by marking certain attributes or methods as private, using the double underscore (__). This ensures that these components are not directly accessible from outside the class. Let's consider an example to illustrate information hiding in encapsulation:

class InformationHidingExample:
    def __init__(self):
        self.__private_var = 10  # private variable

    def get_private_var(self):
        return self.__private_var

    def set_private_var(self, value):
        self.__private_var = value

# Creating an instance of the class
obj = InformationHidingExample()

# Accessing private variable directly (unintended access)
# This will result in an AttributeError
# Uncommenting the next line will raise an error
# print(obj.__private_var)

# Accessing private variable using public methods
print(obj.get_private_var())  # Output: 10

obj.set_private_var(20)
print(obj.get_private_var())  # Output: 20

In this example, the variable __private_var is marked as private, and attempting to access it directly from outside the class will result in an AttributeError. The recommended approach is to use public methods like get_private_var and set_private_var to interact with the private variable. This ensures information hiding by exposing only the necessary functionality and hiding the internal details.

Output:

10
20

3.
How do you achieve encapsulation in Python classes?

Encapsulation in Python is achieved through the use of access modifiers and naming conventions. The two main access modifiers are public and private. Public members are accessible from outside the class, while private members are only accessible within the class. In Python, you can make a member (variable or method) private by prefixing its name with a double underscore (__). This makes it harder to accidentally access or modify the member from outside the class. Let's take a look at an example to demonstrate encapsulation in Python:

class EncapsulationExample:
    def __init__(self):
        self.__private_var = 10  # private variable

    def get_private_var(self):
        return self.__private_var

    def set_private_var(self, value):
        self.__private_var = value

# Creating an instance of the class
obj = EncapsulationExample()

# Accessing private variable directly (unintended access)
# This will result in an AttributeError
# Uncommenting the next line will raise an error
# print(obj.__private_var)

# Accessing private variable using public methods
print(obj.get_private_var())  # Output: 10

obj.set_private_var(20)
print(obj.get_private_var())  # Output: 20

In this example, the variable __private_var is marked as private, and attempting to access it directly from outside the class will result in an AttributeError. The recommended approach is to use public methods like get_private_var and set_private_var to interact with the private variable. This ensures encapsulation by hiding the internal details of the class and exposing only the necessary functionality.

Output:

10
20

4.
Discuss the role of private and protected attributes in encapsulation.

Encapsulation in object-oriented programming involves the bundling of data and methods that operate on the data into a single unit, known as a class. Private and protected attributes are access modifiers in Python that play a crucial role in achieving encapsulation by controlling the visibility and accessibility of class members. 1. Private Attributes: Private attributes are denoted by a double underscore (__). These attributes are not accessible from outside the class and are intended to be used only within the class. This helps in preventing accidental modification of data. 2. Protected Attributes: Protected attributes are denoted by a single underscore (_). While not strictly enforced, they are considered a convention to indicate that an attribute should not be accessed directly from outside the class or subclass. Protected attributes are meant for internal use within the class and its subclasses. Let's explore these concepts with an example:

class EncapsulationExample:
    def __init__(self):
        # Private attribute
        self.__private_var = 10

        # Protected attribute
        self._protected_var = 20

    def get_private_var(self):
        return self.__private_var

    def set_private_var(self, value):
        self.__private_var = value

    def get_protected_var(self):
        return self._protected_var

    def set_protected_var(self, value):
        self._protected_var = value

# Creating an instance of the class
obj = EncapsulationExample()

# Accessing private and protected attributes using public methods
print(obj.get_private_var())     # Output: 10
print(obj.get_protected_var())   # Output: 20

# Modifying private and protected attributes using public methods
obj.set_private_var(30)
obj.set_protected_var(40)

# Displaying the modified values
print(obj.get_private_var())     # Output: 30
print(obj.get_protected_var())   # Output: 40

In this example, __private_var is a private attribute, and _protected_var is a protected attribute. Both are accessed and modified through public methods, ensuring encapsulation. The use of private and protected attributes helps in hiding the internal details of the class, promoting a cleaner and more secure design.

Output:

10
20
30
40