Python Programming - Encapsulation
Exercise : Encapsulation - General Questions
- Encapsulation - General Questions
76.
How can encapsulation be enforced in Python to make a variable 'username' 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 'username' makes it a private variable, enforcing encapsulation within the class.
77.
Consider the following Python code:
class Product:
def __init__(self, name, __price):
self.name = name
self.__price = __price
def set_discount(self, discount):
if 0 < discount < 1:
self.__price *= (1 - discount)
What is the purpose of the set_discount() method?
Answer: Option
Explanation:
The set_discount() method allows setting a new discount for the product with validation, demonstrating encapsulation.
78.
In Python, what is the benefit of using a private variable with a double underscore prefix, such as __total?
class ShoppingCart:
__total = 0
def add_item(self, price):
ShoppingCart.__total += price
Answer: Option
Explanation:
Encapsulation with a double underscore prefix improves code maintainability by hiding the implementation details of the class attribute __total.
79.
What is the primary purpose of the following Python class?
class Movie:
def __init__(self, title, __rating):
self.title = title
self.__rating = __rating
def get_rating(self):
return self.__rating
Answer: Option
Explanation:
The get_rating() method provides controlled and read-only access to the private variable '__rating', demonstrating encapsulation.
80.
How can encapsulation be enforced in Python to make a variable 'email' accessible only within its own class?
class User:
def __init__(self, email, __password):
self.email = email
self.__password = __password
Answer: Option
Explanation:
Adding a double underscore prefix before 'email' makes it a private variable, enforcing encapsulation within the class.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers