Python Programming - Encapsulation
Exercise : Encapsulation - General Questions
- Encapsulation - General Questions
86.
In Python, what is the benefit of using a private variable with a double underscore prefix, such as __quantity?
class Inventory:
__quantity = 0
def update_quantity(self, quantity):
Inventory.__quantity += quantity
Answer: Option
Explanation:
Encapsulation with a double underscore prefix improves code maintainability by hiding the implementation details of the class attribute __quantity.
87.
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
Answer: Option
Explanation:
The get_author() method provides controlled and read-only access to the private variable '__author', demonstrating encapsulation.
88.
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
Answer: Option
Explanation:
Adding a double underscore prefix before 'serial_number' makes it a private variable, enforcing encapsulation within the class.
89.
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?
Answer: Option
Explanation:
The calculate_area() method calculates and returns the area of the circle, demonstrating encapsulation.
90.
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
Answer: Option
Explanation:
Encapsulation with a double underscore prefix improves code maintainability by hiding the implementation details of the class attribute __weight.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers