Python Programming - Encapsulation

Exercise : Encapsulation - General Questions
  • Encapsulation - General Questions
56.
What is the primary purpose of encapsulating the 'balance' variable in the following Python class?
class BankAccount:
    def __init__(self, balance):
        self._balance = balance

    def get_balance(self):
        return self._balance
To create a new instance of the class
To make the 'balance' variable public
To provide controlled access to the 'balance' variable
To allow unrestricted access to the 'balance' variable
Answer: Option
Explanation:
Encapsulation is used to provide controlled access to variables, and in this case, it is applied to the 'balance' variable.

57.
Consider the following Python class:
class Student:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def display_student_info(self):
        return f"Name: {self._name}, Age: {self._age}"
What encapsulation concept is demonstrated in this code?
Public access specifier
Private access specifier
Protected access specifier
Global variable
Answer: Option
Explanation:
The single underscore prefix (_) in the variables _name and _age indicates that they are private variables, demonstrating encapsulation by hiding the implementation details.

58.
In Python, how can encapsulation be enhanced to provide write access to a private variable 'value'?
class Example:
    def __init__(self):
        self._value = 0
Create a setter method for 'value'
Use a double underscore prefix for 'value'
Use a single underscore prefix for 'value'
Make 'value' a global variable
Answer: Option
Explanation:
To provide write access to a private variable, a setter method can be created to set the value.

59.
How can encapsulation help improve code maintenance?
By exposing all internal details of an object
By hiding the implementation details of an object
By making all variables public for easy access
By using global variables extensively
Answer: Option
Explanation:
Encapsulation helps improve code maintenance by hiding the implementation details of an object, making it easier to modify or extend without affecting other parts of the code.

60.
In Python, what is the purpose of using a double underscore prefix before a variable, such as __price?
class Product:
    def __init__(self, name, __price):
        self.name = name
        self.__price = __price
To indicate a public variable
To define a private variable
To create a class method
To allow unrestricted access to the variable
Answer: Option
Explanation:
The double underscore prefix (__price) indicates that it is a private variable, demonstrating encapsulation by hiding the implementation details.