Python Programming - Encapsulation

Exercise : Encapsulation - General Questions
  • Encapsulation - General Questions
61.
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?
To set the age of a person
To retrieve the age of a person
To delete the age of a person
To create a new instance of the class
Answer: Option
Explanation:
The get_age() method is designed to retrieve the private variable __age, demonstrating encapsulation by providing controlled access.

62.
How can encapsulation be achieved in Python to provide read-only access to a variable?
class Example:
    def __init__(self):
        self.__value = 42
Make __value a global variable
Create a getter method for __value
Use a single underscore prefix for __value
Make __value a public variable
Answer: Option
Explanation:
To provide read-only access to a variable, a getter method can be created to retrieve the value.

63.
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
It allows unrestricted access to __count
It improves code maintainability by hiding implementation details
It exposes all internal details of __count
It creates a global variable
Answer: Option
Explanation:
Encapsulation with a double underscore prefix improves code maintainability by hiding the implementation details of the class attribute __count.

64.
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
To create a new instance of the class
To provide a setter method for the celsius variable
To calculate and provide read-only access to the temperature in Fahrenheit
To expose all internal details of the class
Answer: Option
Explanation:
The @property decorator is used to create a read-only property 'fahrenheit' that calculates the temperature in Fahrenheit based on the stored Celsius value.

65.
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?
It creates a new instance of the class
It defines a private variable
It provides a setter method for the balance variable
It allows read-only access to the balance variable
Answer: Option
Explanation:
The @property decorator is used to create a read-only property 'balance', providing controlled access to the private variable '_balance'.