Python Programming - Encapsulation

Exercise : Encapsulation - General Questions
  • Encapsulation - General Questions
6.
What is the purpose of the double underscore prefix in Python, as in __variable?
To indicate a protected variable
To indicate a private variable
To indicate a global variable
To indicate a constant variable
Answer: Option
Explanation:
The double underscore prefix in Python, as in __variable, is used to indicate a private variable.

7.
Which of the following best describes encapsulation?
Combining data and methods into a single unit and allowing unrestricted access to internal details
Hiding implementation details of an object and exposing only the necessary functionalities
Inheriting attributes and behaviors from another class
Using global variables for data encapsulation
Answer: Option
Explanation:
Encapsulation in Python involves hiding the implementation details of an object and exposing only the necessary functionalities.

8.
How can encapsulation be achieved?
By using public access specifiers for all class members
By allowing unrestricted access to the internal details of an object
By using access specifiers to control access to class members
By avoiding the use of classes and objects
Answer: Option
Explanation:
Encapsulation in Python can be achieved by using access specifiers, such as private, protected, and public, to control access to class members.

9.
Which access specifier in Python is used to indicate that a variable or method should be accessible by 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 by subclasses.

10.
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):
        self.__balance += amount

    def withdraw(self, amount):
        if amount <= self.__balance:
            self.__balance -= amount
            return True
        else:
            return False
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 variable __balance indicates that it is a private variable, demonstrating encapsulation by hiding the implementation details.