Exercise: Python

Questions for: Encapsulation

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
What is the purpose of the get_salary() method in this code?
A:
To set the salary of an employee
B:
To delete the salary of an employee
C:
To retrieve the salary of an employee
D:
To create a new instance of the class
Answer: C
The get_salary() method is designed to retrieve the salary of an employee, demonstrating encapsulation by providing controlled access.
In Python, what is the role of a getter method in encapsulation?
A:
To set the value of a private variable
B:
To retrieve the value of a private variable
C:
To create a new instance of a class
D:
To delete a private variable
Answer: B
A getter method in encapsulation is used to retrieve the value of a private variable.
What is a potential advantage of using encapsulation?
A:
Increased code complexity
B:
Improved code maintainability
C:
Reduced data security
D:
Unrestricted access to internal details
Answer: B
Encapsulation in Python can lead to improved code maintainability by organizing code into a more modular and understandable structure.
Which of the following access specifiers in Python is used to indicate that a variable or method should be accessible only within its own class and not from outside?
A:
Public
B:
Private
C:
Protected
D:
Global
Answer: B
The private access specifier in Python (indicated by a single underscore or double underscore prefix) restricts access to variables and methods only within their own class.
What does the term "encapsulation" mean in the context of object-oriented programming?
A:
Combining multiple classes into one
B:
Hiding the implementation details of an object and bundling data and methods into a single unit
C:
Inheriting attributes from multiple classes
D:
Exposing all internal details of an object
Answer: B
Encapsulation in Python involves hiding the implementation details of an object and bundling data and methods into a single unit for better control.
Ad Slot (Above Pagination)
Quiz