Exercise: Encapsulation
Questions for: Encapsulation
Consider the following Python code:
class Triangle:
def __init__(self, __base, __height):
self.__base = __base
self.__height = __height
def calculate_area(self):
return 0.5 * self.__base * self.__height
What is the purpose of the calculate_area() method?
A:
To retrieve the area of the triangle
B:
To set a new area for the triangle
C:
To calculate the area of the triangle
D:
To expose all internal details of the class
Answer: C
The calculate_area() method calculates and returns the area of the triangle, demonstrating encapsulation.
How can encapsulation be enforced in Python to make a variable 'product_code' accessible only within its own class?
class Product:
def __init__(self, product_code, __price):
self.product_code = product_code
self.__price = __price
A:
Use a getter method for 'product_code'
B:
Add a single underscore prefix before 'product_code'
C:
Make 'product_code' a global variable
D:
Add a double underscore prefix before 'product_code'
Answer: D
Adding a double underscore prefix before 'product_code' makes it a private variable, enforcing encapsulation within the class.
Discuss About this Question.
What is the primary purpose of the following Python class?
class Car:
def __init__(self, model, __speed):
self.model = model
self.__speed = __speed
def get_speed(self):
return self.__speed
A:
To create a new instance of the class
B:
To provide controlled access to the 'speed' variable
C:
To define a public variable 'speed'
D:
To allow unrestricted access to the 'speed' variable
Answer: B
The get_speed() method provides controlled and read-only access to the private variable '__speed', demonstrating encapsulation.
Discuss About this Question.
In Python, what is the benefit of using a private variable with a double underscore prefix, such as __inventory_count?
class Product:
__inventory_count = 0
def update_inventory(self, count):
Product.__inventory_count += count
A:
It improves code maintainability by hiding implementation details
B:
It allows unrestricted access to __inventory_count
C:
It exposes all internal details of __inventory_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 __inventory_count.
Discuss About this Question.
Consider the following Python code:
class Rectangle:
def __init__(self, __length, __width):
self.__length = __length
self.__width = __width
def calculate_area(self):
return self.__length * self.__width
What is the purpose of the calculate_area() method?
A:
To retrieve the area of the rectangle
B:
To set a new area for the rectangle
C:
To calculate the area of the rectangle
D:
To expose all internal details of the class
Answer: C
The calculate_area() method calculates and returns the area of the rectangle, demonstrating encapsulation.
Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.