Python Programming - Encapsulation

Exercise : Encapsulation - General Questions
  • Encapsulation - General Questions
16.
In Python, what is the purpose of the __init__() method in the context of encapsulation?
To initialize a class instance with default values
To define a private variable
To create a new instance of the class
To hide the implementation details of a class
Answer: Option
Explanation:
The __init__() method in Python is used to initialize a class instance with default values, contributing to encapsulation.

17.
Which of the following statements about encapsulation in Python is true?
Encapsulation allows unrestricted access to the internal details of an object.
Encapsulation involves exposing all implementation details of an object.
Encapsulation is achieved through the use of global variables.
Encapsulation contributes to data security by hiding implementation details.
Answer: Option
Explanation:
Encapsulation contributes to data security by hiding the implementation details of an object, preventing direct access and manipulation.

18.
Which access specifier in Python is used to indicate that a variable or method should be accessible within the same class and its subclasses?
Public
Private
Protected
Global
Answer: Option
Explanation:
Protected access specifier in Python is denoted by a single underscore (_), and it indicates that the variable or method should be accessible within the same class and its subclasses.

19.
What is the role of the @staticmethod decorator in encapsulation?
To define a private variable
To create a class instance
To provide a static method for a class
To access a global variable
Answer: Option
Explanation:
The @staticmethod decorator is used in encapsulation to provide a static method for a class, allowing functionality without accessing instance-specific data.

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

    def set_salary(self, new_salary):
        if new_salary > 0:
            self._salary = new_salary
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 _salary indicates that they are protected variables, demonstrating encapsulation by hiding the implementation details.