Python Programming - Encapsulation
Exercise : Encapsulation - General Questions
- Encapsulation - General Questions
91.
What is the primary purpose of the following Python class?
class Student:
def __init__(self, name, __grade):
self.name = name
self.__grade = __grade
def get_grade(self):
return self.__grade
Answer: Option
Explanation:
The get_grade() method provides controlled and read-only access to the private variable '__grade', demonstrating encapsulation.
92.
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
Answer: Option
Explanation:
Adding a double underscore prefix before 'employee_id' makes it a private variable, enforcing encapsulation within the class.
93.
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?
Answer: Option
Explanation:
The calculate_area() method calculates and returns the area of the rectangle, demonstrating encapsulation.
94.
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
Answer: Option
Explanation:
Encapsulation with a double underscore prefix improves code maintainability by hiding the implementation details of the class attribute __inventory_count.
95.
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
Answer: Option
Explanation:
The get_speed() method provides controlled and read-only access to the private variable '__speed', demonstrating encapsulation.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers