Python Programming - Encapsulation

Exercise : Encapsulation - General Questions
  • Encapsulation - General Questions
26.
In Python, what does the double underscore prefix in a variable, like __variable, indicate?
A protected variable
A private variable
A global variable
A constant variable
Answer: Option
Explanation:
The double underscore prefix in Python, as in __variable, indicates a private variable.

27.
What is the primary benefit of using encapsulation in object-oriented programming?
It allows unrestricted access to the internal details of an object.
It promotes code reusability.
It enhances data security by hiding implementation details.
It simplifies the process of class instantiation.
Answer: Option
Explanation:
The primary benefit of using encapsulation is that it enhances data security by hiding the implementation details of an object.

28.
Which of the following is true about encapsulation?
It involves exposing all implementation details of an object.
It is achieved through the use of global variables.
It allows for unrestricted access to internal details of an object.
It combines data and methods into a single unit and hides implementation details.
Answer: Option
Explanation:
Encapsulation in Python combines data and methods into a single unit and hides implementation details.

29.
What is the role of a setter method in encapsulation?
To retrieve the value of a private variable.
To provide a static method for a class.
To set the value of a private variable with validation.
To define a private variable.
Answer: Option
Explanation:
A setter method in encapsulation is used to set the value of a private variable with validation, ensuring controlled access.

30.
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?
Public access specifier
Private access specifier
Protected access specifier
Global variable
Answer: Option
Explanation:
The single underscore prefix (_) in the variables _name and _age indicates that they are private variables, demonstrating encapsulation by hiding the implementation details.