Python Programming - Encapsulation
Exercise : Encapsulation - General Questions
- Encapsulation - General Questions
81.
Consider the following Python code:
class BankAccount:
def __init__(self, balance):
self._balance = balance
def withdraw(self, amount):
if amount <= self._balance:
self._balance -= amount
return amount
else:
return "Insufficient funds"
What encapsulation concept is demonstrated in this code?
Answer: Option
Explanation:
The single underscore prefix before 'balance' indicates that it is a public variable, allowing access outside the class.
82.
In Python, what is the benefit of using a private variable with a double underscore prefix, such as __quantity?
class Inventory:
__quantity = 0
def update_quantity(self, quantity):
Inventory.__quantity += quantity
Answer: Option
Explanation:
Encapsulation with a double underscore prefix improves code maintainability by hiding the implementation details of the class attribute __quantity.
83.
What is the primary purpose of the following Python class?
class Wallet:
def __init__(self, owner, __balance):
self.owner = owner
self.__balance = __balance
def get_balance(self):
return self.__balance
Answer: Option
Explanation:
The get_balance() method provides controlled and read-only access to the private variable '__balance', demonstrating encapsulation.
84.
How can encapsulation be enforced in Python to make a variable 'account_number' accessible only within its own class?
class BankAccount:
def __init__(self, account_number, __balance):
self.account_number = account_number
self.__balance = __balance
Answer: Option
Explanation:
Adding a double underscore prefix before 'account_number' makes it a private variable, enforcing encapsulation within the class.
85.
Consider the following Python code:
class Temperature:
def __init__(self, __celsius):
self.__celsius = __celsius
def to_fahrenheit(self):
return (self.__celsius * 9/5) + 32
What is the purpose of the to_fahrenheit() method?
Answer: Option
Explanation:
The to_fahrenheit() method converts the temperature from Celsius to Fahrenheit, demonstrating encapsulation.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers