Exercise: Encapsulation
Questions for: Encapsulation
What is the role of the
@classmethod decorator in encapsulation?
A:
To define a private variable
B:
To create a class instance
C:
To provide a class method for a class
D:
To access a global variable
Answer: C
The
@classmethod decorator is used in encapsulation to provide a class method for a class, allowing functionality related to the class.
How does encapsulation contribute to code maintainability in object-oriented programming?
A:
By exposing all implementation details of an object
B:
By combining data and methods into a single unit
C:
By allowing unrestricted access to internal details of an object
D:
By hiding the implementation details of an object
Answer: B
Encapsulation contributes to code maintainability by combining data and methods into a single unit, making the code more modular and easier to manage.
Discuss About this Question.
Which access specifier in Python is used to indicate that a variable or method should not be accessed from outside the class?
A:
Public
B:
Private
C:
Protected
D:
Global
Answer: B
Private access specifier in Python is used to indicate that a variable or method should not be accessed from outside the class.
Discuss About this Question.
What is the primary purpose of encapsulation?
A:
To allow unrestricted access to class members
B:
To combine data and methods into a single unit
C:
To create multiple instances of a class
D:
To expose all implementation details of an object
Answer: B
The primary purpose of encapsulation in Python is to combine data and methods into a single unit, promoting modularity.
Discuss About this Question.
Consider the following Python code:
class Employee:
def __init__(self, name, salary):
self._name = name
self._salary = salary
def get_salary(self):
return self._salary
def set_salary(self, new_salary):
if new_salary > 0:
self._salary = new_salary
What concept of encapsulation is demonstrated in this code?
A:
Public access specifier
B:
Private access specifier
C:
Protected access specifier
D:
Global variable
Answer: C
The single underscore prefix (
_) in the variables _name and _salary indicates that they are protected variables, demonstrating encapsulation by hiding the implementation details.Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.