Python Programming - Encapsulation
Exercise : Encapsulation - General Questions
- Encapsulation - General Questions
96.
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
Answer: Option
Explanation:
Adding a double underscore prefix before 'product_code' makes it a private variable, enforcing encapsulation within the class.
97.
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?
Answer: Option
Explanation:
The calculate_area() method calculates and returns the area of the triangle, demonstrating encapsulation.
98.
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
Answer: Option
Explanation:
Encapsulation with a double underscore prefix improves code maintainability by hiding the implementation details of the class attribute __stock_quantity.
99.
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
Answer: Option
Explanation:
The get_age() method provides controlled and read-only access to the private variable '__age', demonstrating encapsulation.
100.
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
Answer: Option
Explanation:
Adding a double underscore prefix before 'reservation_code' makes it a private variable, enforcing encapsulation within the class.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers