Python Programming - Encapsulation

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

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

    def set_discount(self, discount):
        if 0 < discount < 1:
            self.__price *= (1 - discount)
What is the purpose of the set_discount() method?
To retrieve the price of the product
To set a new discount 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_discount() method allows setting a new discount for the product with validation, demonstrating encapsulation.

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

    def add_item(self, price):
        ShoppingCart.__total += price
It improves code maintainability by hiding implementation details
It allows unrestricted access to __total
It exposes all internal details of __total
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 __total.

79.
What is the primary purpose of the following Python class?
class Movie:
    def __init__(self, title, __rating):
        self.title = title
        self.__rating = __rating

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

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