Exercise: Python

Questions for: Encapsulation

How can encapsulation be enforced in Python to make a variable 'employee_id' accessible only within its own class?
class Employee:
    def __init__(self, employee_id, __salary):
        self.employee_id = employee_id
        self.__salary = __salary
A:
Use a getter method for 'employee_id'
B:
Add a single underscore prefix before 'employee_id'
C:
Make 'employee_id' a global variable
D:
Add a double underscore prefix before 'employee_id'
Answer: D
Adding a double underscore prefix before 'employee_id' makes it a private variable, enforcing encapsulation within the class.
In Python, what is the benefit of using a private variable with a double underscore prefix, such as __weight?
class Product:
    __weight = 0

    def update_weight(self, weight):
        Product.__weight += weight
A:
It improves code maintainability by hiding implementation details
B:
It allows unrestricted access to __weight
C:
It exposes all internal details of __weight
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 __weight.
Consider the following Python code:
class Circle:
    def __init__(self, __radius):
        self.__radius = __radius

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

    def get_author(self):
        return self.__author
A:
To create a new instance of the class
B:
To provide controlled access to the 'author' variable
C:
To define a public variable 'author'
D:
To allow unrestricted access to the 'author' variable
Answer: B
The get_author() method provides controlled and read-only access to the private variable '__author', demonstrating encapsulation.
Ad Slot (Above Pagination)
Quiz