Python Programming - Encapsulation

Exercise : Encapsulation - General Questions
  • Encapsulation - General Questions
51.
In Python, what is the purpose of the @property decorator in a class?
To create a new instance of a class
To provide a getter method for a private variable
To define a private variable
To access a global variable
Answer: Option
Explanation:
The @property decorator is used in Python to create a getter method for a private variable, allowing controlled access.

52.
What is the primary purpose of using encapsulation in object-oriented programming?
To expose all implementation details of an object
To hide the implementation details of an object and bundle data and methods into a single unit
To create global variables for easy access
To increase code complexity
Answer: Option
Explanation:
The primary purpose of encapsulation is to hide the implementation details of an object and bundle data and methods into a single unit.

53.
Which of the following statements is true regarding encapsulation?
It encourages exposing all internal details of an object.
It is achieved through the use of global variables.
It involves combining data and methods into a single unit and hiding implementation details.
It promotes code complexity by making all variables public.
Answer: Option
Explanation:
Encapsulation in Python involves combining data and methods into a single unit and hiding implementation details.

54.
Which of the following access specifiers in Python allows a variable or method to be accessible within its own class and its subclasses?
Public
Private
Protected
Global
Answer: Option
Explanation:
The protected access specifier in Python allows a variable or method to be accessible within its own class and its subclasses.

55.
Consider the following Python code:
class Car:
    def __init__(self, model, speed):
        self._model = model
        self._speed = speed

    def display_info(self):
        return f"Model: {self._model}, Speed: {self._speed} km/h"
What encapsulation concept is demonstrated in this code?
Public access specifier
Private access specifier
Protected access specifier
Global variable
Answer: Option
Explanation:
The single underscore prefix (_) in the variables _model and _speed indicates that they are private variables, demonstrating encapsulation by hiding the implementation details.