Exercise: Python

Questions for: Encapsulation

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?
A:
To retrieve the temperature in Fahrenheit
B:
To set a new temperature in Fahrenheit
C:
To convert the temperature to Fahrenheit
D:
To expose all internal details of the class
Answer: C
The to_fahrenheit() method converts the temperature from Celsius to Fahrenheit, demonstrating encapsulation.
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
A:
Use a getter method for 'account_number'
B:
Add a single underscore prefix before 'account_number'
C:
Make 'account_number' a global variable
D:
Add a double underscore prefix before 'account_number'
Answer: D
Adding a double underscore prefix before 'account_number' makes it a private variable, enforcing encapsulation within the class.
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
A:
To create a new instance of the class
B:
To provide controlled access to the 'balance' variable
C:
To define a public variable 'balance'
D:
To allow unrestricted access to the 'balance' variable
Answer: B
The get_balance() method provides controlled and read-only access to the private variable '__balance', demonstrating encapsulation.
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
A:
It improves code maintainability by hiding implementation details
B:
It allows unrestricted access to __quantity
C:
It exposes all internal details of __quantity
D:
It creates a global variable
Answer: A
Encapsulation with a double underscore prefix improves code maintainability by hiding the implementation details of the class attribute __quantity.
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?
A:
Public access specifier
B:
Private access specifier
C:
Protected access specifier
D:
Global variable
Answer: A
The single underscore prefix before 'balance' indicates that it is a public variable, allowing access outside the class.
Ad Slot (Above Pagination)
Quiz