Exercise: Python

Questions for: Encapsulation

How does encapsulation contribute to code maintenance?
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 maintenance in Python by combining data and methods into a single unit, making the code more modular and easier to manage.
Which of the following is a common guideline when using encapsulation?
A:
Avoid using private variables altogether.
B:
Make all variables public for ease of access.
C:
Provide getter and setter methods for private variables as needed.
D:
Use global variables extensively.
Answer: C
A common guideline when using encapsulation is to provide getter and setter methods for private variables as needed to control access.
In Python, what is a potential drawback of using encapsulation?
A:
Reduced code modularity
B:
Increased code complexity
C:
Enhanced data security
D:
Improved code readability
Answer: B
A potential drawback of using encapsulation in Python is increased code complexity, especially if not managed properly.
What is the purpose of the @property decorator in encapsulation?
A:
To create a new instance of a class
B:
To provide a getter method for a private variable
C:
To access a global variable
D:
To define a private variable
Answer: B
The @property decorator in encapsulation is used to provide a getter method for a private variable, allowing controlled access.
Consider the following Python code:
class Student:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def get_name(self):
        return self._name

    def set_age(self, new_age):
        if new_age >= 0:
            self._age = new_age
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: B
The single underscore prefix (_) in the variables _name and _age indicates that they are private variables, demonstrating encapsulation by hiding the implementation details.
Ad Slot (Above Pagination)
Quiz