Exercise: Python

Questions for: Encapsulation

Consider the following Python class:
class BankAccount:
    def __init__(self, balance):
        self._balance = balance

    @property
    def balance(self):
        return self._balance
What does the @property decorator do in this code?
A:
It creates a new instance of the class
B:
It defines a private variable
C:
It provides a setter method for the balance variable
D:
It allows read-only access to the balance variable
Answer: D
The @property decorator is used to create a read-only property 'balance', providing controlled access to the private variable '_balance'.
What is the purpose of the following Python code?
class TemperatureConverter:
    def __init__(self, celsius):
        self._celsius = celsius

    @property
    def fahrenheit(self):
        return self._celsius * 9/5 + 32
A:
To create a new instance of the class
B:
To provide a setter method for the celsius variable
C:
To calculate and provide read-only access to the temperature in Fahrenheit
D:
To expose all internal details of the class
Answer: C
The @property decorator is used to create a read-only property 'fahrenheit' that calculates the temperature in Fahrenheit based on the stored Celsius value.
What is the advantage of encapsulating a class attribute with a double underscore prefix, such as __count?
class MyClass:
    __count = 0

    def increment_count(self):
        MyClass.__count += 1
A:
It allows unrestricted access to __count
B:
It improves code maintainability by hiding implementation details
C:
It exposes all internal details of __count
D:
It creates a global variable
Answer: B
Encapsulation with a double underscore prefix improves code maintainability by hiding the implementation details of the class attribute __count.
How can encapsulation be achieved in Python to provide read-only access to a variable?
class Example:
    def __init__(self):
        self.__value = 42
A:
Make __value a global variable
B:
Create a getter method for __value
C:
Use a single underscore prefix for __value
D:
Make __value a public variable
Answer: B
To provide read-only access to a variable, a getter method can be created to retrieve the value.
Consider the following Python code:
class Person:
    def __init__(self, name, __age):
        self.name = name
        self.__age = __age

    def get_age(self):
        return self.__age
What is the purpose of the get_age() method?
A:
To set the age of a person
B:
To retrieve the age of a person
C:
To delete the age of a person
D:
To create a new instance of the class
Answer: B
The get_age() method is designed to retrieve the private variable __age, demonstrating encapsulation by providing controlled access.
Ad Slot (Above Pagination)
Quiz