Exercise: Python

Questions for: Encapsulation

In Python, what is the benefit of using a private variable with a double underscore prefix, such as __song_count?
class MusicLibrary:
    __song_count = 0

    def update_count(self, count):
        MusicLibrary.__song_count += count
A:
It improves code maintainability by hiding implementation details
B:
It allows unrestricted access to __song_count
C:
It exposes all internal details of __song_count
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 __song_count.
Consider the following Python code:
class Square:
    def __init__(self, __side_length):
        self.__side_length = __side_length

    def calculate_area(self):
        return self.__side_length ** 2
What is the purpose of the calculate_area() method?
A:
To retrieve the area of the square
B:
To set a new area for the square
C:
To calculate the area of the square
D:
To expose all internal details of the class
Answer: C
The calculate_area() method calculates and returns the area of the square, demonstrating encapsulation.
How can encapsulation be enforced in Python to make a variable 'reservation_code' accessible only within its own class?
class Reservation:
    def __init__(self, reservation_code, __status):
        self.reservation_code = reservation_code
        self.__status = __status
A:
Use a getter method for 'reservation_code'
B:
Add a single underscore prefix before 'reservation_code'
C:
Make 'reservation_code' a global variable
D:
Add a double underscore prefix before 'reservation_code'
Answer: D
Adding a double underscore prefix before 'reservation_code' makes it a private variable, enforcing encapsulation within the class.
What is the primary purpose of the following Python class?
class Person:
    def __init__(self, name, __age):
        self.name = name
        self.__age = __age

    def get_age(self):
        return self.__age
A:
To create a new instance of the class
B:
To provide controlled access to the 'age' variable
C:
To define a public variable 'age'
D:
To allow unrestricted access to the 'age' variable
Answer: B
The get_age() method provides controlled and read-only access to the private variable '__age', demonstrating encapsulation.
In Python, what is the benefit of using a private variable with a double underscore prefix, such as __stock_quantity?
class Inventory:
    __stock_quantity = 0

    def update_stock(self, quantity):
        Inventory.__stock_quantity += quantity
A:
It improves code maintainability by hiding implementation details
B:
It allows unrestricted access to __stock_quantity
C:
It exposes all internal details of __stock_quantity
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 __stock_quantity.
Ad Slot (Above Pagination)
Quiz