Python Programming - Encapsulation

Exercise : Encapsulation - General Questions
  • Encapsulation - General Questions
21.
What is the primary purpose of encapsulation?
To allow unrestricted access to class members
To combine data and methods into a single unit
To create multiple instances of a class
To expose all implementation details of an object
Answer: Option
Explanation:
The primary purpose of encapsulation in Python is to combine data and methods into a single unit, promoting modularity.

22.
Which access specifier in Python is used to indicate that a variable or method should not be accessed from outside the class?
Public
Private
Protected
Global
Answer: Option
Explanation:
Private access specifier in Python is used to indicate that a variable or method should not be accessed from outside the class.

23.
How does encapsulation contribute to code maintainability in object-oriented programming?
By exposing all implementation details of an object
By combining data and methods into a single unit
By allowing unrestricted access to internal details of an object
By hiding the implementation details of an object
Answer: Option
Explanation:
Encapsulation contributes to code maintainability by combining data and methods into a single unit, making the code more modular and easier to manage.

24.
What is the role of the @classmethod decorator in encapsulation?
To define a private variable
To create a class instance
To provide a class method for a class
To access a global variable
Answer: Option
Explanation:
The @classmethod decorator is used in encapsulation to provide a class method for a class, allowing functionality related to the class.

25.
Consider the following Python code:
class Car:
    def __init__(self, model, year):
        self.__model = model
        self.__year = year

    def display_info(self):
        return f"Model: {self.__model}, Year: {self.__year}"
What concept of encapsulation is demonstrated in this code?
Public access specifier
Private access specifier
Protected access specifier
Global variable
Answer: Option
Explanation:
The double underscore prefix (__) in the variables __model and __year indicates that they are private variables, demonstrating encapsulation by hiding the implementation details.