Python Programming - Encapsulation
Exercise : Encapsulation - General Questions
- Encapsulation - General Questions
66.
How can encapsulation be enforced 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.
67.
In Python, what is the primary benefit of using a property with a setter method?
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
@property
def area(self):
return self._width * self._height
@property
def width(self):
return self._width
@width.setter
def width(self, value):
if value > 0:
self._width = value
else:
raise ValueError("Width must be greater than 0.")
Answer: Option
Explanation:
The @width.setter decorator allows write access to the 'width' property with the provided validation in the setter method.
68.
What does the following Python code demonstrate?
class Book:
def __init__(self, title, __author):
self.title = title
self.__author = __author
def get_author(self):
return self.__author
Answer: Option
Explanation:
The double underscore prefix before 'author' indicates that it is a private variable, demonstrating encapsulation by hiding the implementation details.
69.
How can encapsulation be enhanced in the following Python class to provide write access to the 'price' variable?
class Product:
def __init__(self, name, price):
self.name = name
self.__price = price
Answer: Option
Explanation:
To provide write access to a private variable, a setter method can be created for 'price'.
70.
What is the purpose of the following Python code?
class Employee:
def __init__(self, name, __salary):
self.name = name
self.__salary = __salary
@property
def salary(self):
return self.__salary
Answer: Option
Explanation:
The @property decorator creates a read-only property 'salary', providing controlled access to the private variable '__salary'.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers