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
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?
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
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?
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
Answer: Option
Explanation:
The double underscore prefix (__price) indicates that it is a private variable, demonstrating encapsulation by hiding the implementation details.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers