Python Programming - Encapsulation

Exercise : Encapsulation - General Questions
  • Encapsulation - General Questions
71.
What is the primary purpose of the following Python class?
class Student:
    def __init__(self, name, __grade):
        self.name = name
        self.__grade = __grade

    def get_grade(self):
        return self.__grade
To create a new instance of the class
The get_grade() method provides access to the private variable 'grade'
To define a public variable 'grade'
To allow unrestricted access to the 'grade' variable
Answer: Option
Explanation:
The get_grade() method provides access to the private variable '__grade', demonstrating encapsulation.

72.
How can encapsulation be enforced in Python to make a variable 'password' accessible only within its own class?
class User:
    def __init__(self, username, password):
        self.username = username
        self.__password = password
Use a getter method for 'password'
Add a single underscore prefix before 'password'
Make 'password' a global variable
Add a double underscore prefix before 'password'
Answer: Option
Explanation:
Adding a double underscore prefix before 'password' makes it a private variable, enforcing encapsulation within the class.

73.
Consider the following Python code:
class Product:
    def __init__(self, name, __price):
        self.name = name
        self.__price = __price

    def set_price(self, new_price):
        if new_price > 0:
            self.__price = new_price
What is the purpose of the set_price() method?
To retrieve the price of the product
To set a new price for the product with validation
To create a new instance of the class
To expose all internal details of the class
Answer: Option
Explanation:
The set_price() method allows setting a new price for the product with validation, demonstrating encapsulation.

74.
In Python, what is the benefit of using a private variable with a double underscore prefix, such as __count?
class Counter:
    __count = 0

    def increment_count(self):
        Counter.__count += 1
It improves code maintainability by hiding implementation details
It allows unrestricted access to __count
It exposes all internal details of __count
It creates a global variable
Answer: Option
Explanation:
Encapsulation with a double underscore prefix improves code maintainability by hiding the implementation details of the class attribute __count.

75.
What is the primary purpose of the following Python class?
class Car:
    def __init__(self, make, __model):
        self.make = make
        self.__model = __model

    def get_model(self):
        return self.__model
To create a new instance of the class
To provide controlled access to the 'model' variable
To define a public variable 'model'
To allow unrestricted access to the 'model' variable
Answer: Option
Explanation:
The get_model() method provides controlled and read-only access to the private variable '__model', demonstrating encapsulation.