Python Programming - Encapsulation
Exercise : Encapsulation - General Questions
- Encapsulation - General Questions
71.
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 access to the private variable '__grade', demonstrating encapsulation.
72.
How can encapsulation be enforced in Python to make a variable 'password' accessible only within its own class?
class User:
def __init__(self, username, password):
self.username = username
self.__password = password
Answer: Option
Explanation:
Adding a double underscore prefix before 'password' makes it a private variable, enforcing encapsulation within the class.
73.
Consider the following Python code:
class Product:
def __init__(self, name, __price):
self.name = name
self.__price = __price
def set_price(self, new_price):
if new_price > 0:
self.__price = new_price
What is the purpose of the set_price() method?
Answer: Option
Explanation:
The set_price() method allows setting a new price for the product with validation, demonstrating encapsulation.
74.
In Python, what is the benefit of using a private variable with a double underscore prefix, such as __count?
class Counter:
__count = 0
def increment_count(self):
Counter.__count += 1
Answer: Option
Explanation:
Encapsulation with a double underscore prefix improves code maintainability by hiding the implementation details of the class attribute __count.
75.
What is the primary purpose of the following Python class?
class Car:
def __init__(self, make, __model):
self.make = make
self.__model = __model
def get_model(self):
return self.__model
Answer: Option
Explanation:
The get_model() method provides controlled and read-only access to the private variable '__model', demonstrating encapsulation.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers