Exercise: Encapsulation
Questions for: Encapsulation
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?
A:
Public access specifier
B:
Private access specifier
C:
Protected access specifier
D:
Global variable
Answer: B
The single underscore prefix (
_) in the variables _model and _speed indicates that they are private variables, demonstrating encapsulation by hiding the implementation details.
Which of the following access specifiers in Python allows a variable or method to be accessible within its own class and its subclasses?
A:
Public
B:
Private
C:
Protected
D:
Global
Answer: C
The protected access specifier in Python allows a variable or method to be accessible within its own class and its subclasses.
Discuss About this Question.
Which of the following statements is true regarding encapsulation?
A:
It encourages exposing all internal details of an object.
B:
It is achieved through the use of global variables.
C:
It involves combining data and methods into a single unit and hiding implementation details.
D:
It promotes code complexity by making all variables public.
Answer: C
Encapsulation in Python involves combining data and methods into a single unit and hiding implementation details.
Discuss About this Question.
What is the primary purpose of using encapsulation in object-oriented programming?
A:
To expose all implementation details of an object
B:
To hide the implementation details of an object and bundle data and methods into a single unit
C:
To create global variables for easy access
D:
To increase code complexity
Answer: B
The primary purpose of encapsulation is to hide the implementation details of an object and bundle data and methods into a single unit.
Discuss About this Question.
In Python, what is the purpose of the
@property decorator in a class?
A:
To create a new instance of a class
B:
To provide a getter method for a private variable
C:
To define a private variable
D:
To access a global variable
Answer: B
The
@property decorator is used in Python to create a getter method for a private variable, allowing controlled access.Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.