Exercise: Python

Questions for: Encapsulation

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
A:
Use a getter method for 'email'
B:
Add a single underscore prefix before 'email'
C:
Make 'email' a global variable
D:
Add a double underscore prefix before 'email'
Answer: D
Adding a double underscore prefix before 'email' makes it a private variable, enforcing encapsulation within the class.
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
A:
To create a new instance of the class
B:
To provide controlled access to the 'rating' variable
C:
To define a public variable 'rating'
D:
To allow unrestricted access to the 'rating' variable
Answer: B
The get_rating() method provides controlled and read-only access to the private variable '__rating', demonstrating encapsulation.
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
A:
It improves code maintainability by hiding implementation details
B:
It allows unrestricted access to __total
C:
It exposes all internal details of __total
D:
It creates a global variable
Answer: A
Encapsulation with a double underscore prefix improves code maintainability by hiding the implementation details of the class attribute __total.
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?
A:
To retrieve the price of the product
B:
To set a new discount for the product with validation
C:
To create a new instance of the class
D:
To expose all internal details of the class
Answer: B
The set_discount() method allows setting a new discount for the product with validation, demonstrating encapsulation.
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
A:
Use a getter method for 'username'
B:
Add a single underscore prefix before 'username'
C:
Make 'username' a global variable
D:
Add a double underscore prefix before 'username'
Answer: D
Adding a double underscore prefix before 'username' makes it a private variable, enforcing encapsulation within the class.
Ad Slot (Above Pagination)
Quiz