Python Programming - Encapsulation

Exercise : Encapsulation - General Questions
  • Encapsulation - General Questions
101.
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?
To retrieve the area of the square
To set a new area for the square
To calculate the area of the square
To expose all internal details of the class
Answer: Option
Explanation:
The calculate_area() method calculates and returns the area of the square, demonstrating encapsulation.

102.
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
It improves code maintainability by hiding implementation details
It allows unrestricted access to __song_count
It exposes all internal details of __song_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 __song_count.