Python Programming - Encapsulation

Exercise : Encapsulation - General Questions
  • Encapsulation - General Questions
41.
Which of the following is a benefit of encapsulation?
Increased code complexity
Improved code reusability
Reduced data security
Unrestricted access to internal details
Answer: Option
Explanation:
Encapsulation in Python promotes improved code reusability by encapsulating data and methods into a single unit.

42.
In Python, what is the purpose of the __str__() method in a class?
To create a new instance of a class
To define a private variable
To provide a string representation of the object
To access a global variable
Answer: Option
Explanation:
The __str__() method in Python is used to provide a string representation of the object when the str() function is called.

43.
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.

44.
What is the purpose of using encapsulation?
To increase code complexity
To combine data and methods into a single unit
To expose all implementation details of an object
To make all variables public for easy access
Answer: Option
Explanation:
The purpose of using encapsulation in Python is to combine data and methods into a single unit, promoting modularity.

45.
Consider the following Python code:
class Customer:
    def __init__(self, name, email):
        self._name = name
        self._email = email

    def display_info(self):
        return f"Name: {self._name}, Email: {self._email}"
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 _email indicates that they are private variables, demonstrating encapsulation by hiding the implementation details.