Python Programming - Encapsulation

Exercise : Encapsulation - General Questions
  • Encapsulation - General Questions
36.
Which keyword in Python is used to define a private variable within a class?
private
secret
protected
None of the above
Answer: Option
Explanation:
In Python, there is no explicit keyword for defining private variables. Conventionally, a single or double underscore prefix is used to indicate privacy, but it is a convention and not a strict rule.

37.
In Python, what is the purpose of using a double underscore prefix in a method name, such as __method()?
To define a private method
To create a public method
To indicate a class method
To access a global method
Answer: Option
Explanation:
The double underscore prefix in a method name in Python, such as __method(), is used to define a private method.

38.
Which statement accurately describes the concept of encapsulation?
Encapsulation involves exposing all implementation details of an object.
Encapsulation is a mechanism for achieving multiple inheritances.
Encapsulation combines data and methods into a single unit and hides implementation details.
Encapsulation is only applicable to global variables.
Answer: Option
Explanation:
Encapsulation in Python combines data and methods into a single unit and hides implementation details.

39.
What is the role of a getter method in encapsulation?
To set the value of a private variable
To retrieve the value of a private variable
To create a new instance of a class
To delete a private variable
Answer: Option
Explanation:
A getter method in encapsulation is used to retrieve the value of a private variable.

40.
Consider the following Python code:
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance

    def get_balance(self):
        return self.__balance

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
What is the encapsulation concept demonstrated in this code?
Public access specifier
Private access specifier
Protected access specifier
Global variable
Answer: Option
Explanation:
The double underscore prefix in the variable __balance indicates that it is a private variable, demonstrating the encapsulation concept of private access.