Exercise: Python

Questions for: Encapsulation

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
A:
To indicate a public variable
B:
To define a private variable
C:
To create a class method
D:
To allow unrestricted access to the variable
Answer: B
The double underscore prefix (__price) indicates that it is a private variable, demonstrating encapsulation by hiding the implementation details.
How can encapsulation help improve code maintenance?
A:
By exposing all internal details of an object
B:
By hiding the implementation details of an object
C:
By making all variables public for easy access
D:
By using global variables extensively
Answer: B
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.
In Python, how can encapsulation be enhanced to provide write access to a private variable 'value'?
class Example:
    def __init__(self):
        self._value = 0
A:
Create a setter method for 'value'
B:
Use a double underscore prefix for 'value'
C:
Use a single underscore prefix for 'value'
D:
Make 'value' a global variable
Answer: A
To provide write access to a private variable, a setter method can be created to set the value.
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?
A:
Public access specifier
B:
Private access specifier
C:
Protected access specifier
D:
Global variable
Answer: B
The single underscore prefix (_) in the variables _name and _age indicates that they are private variables, demonstrating encapsulation by hiding the implementation details.
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
A:
To create a new instance of the class
B:
To make the 'balance' variable public
C:
To provide controlled access to the 'balance' variable
D:
To allow unrestricted access to the 'balance' variable
Answer: C
Encapsulation is used to provide controlled access to variables, and in this case, it is applied to the 'balance' variable.
Ad Slot (Above Pagination)
Quiz