Exercise: Encapsulation
Questions for: Encapsulation
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
A:
To create a new instance of the class
B:
To define a public variable 'salary'
C:
To allow unrestricted access to the 'salary' variable
D:
To provide read-only access to the 'salary' variable
Answer: D
The @property decorator creates a read-only property 'salary', providing controlled access to the private variable '__salary'.
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
A:
Use a double underscore prefix for 'price'
B:
Create a setter method for 'price'
C:
Make 'price' a global variable
D:
Use a single underscore prefix for 'price'
Answer: B
To provide write access to a private variable, a setter method can be created for 'price'.
Discuss About this Question.
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
A:
Public access specifier
B:
Private access specifier
C:
Protected access specifier
D:
Global variable
Answer: B
The double underscore prefix before 'author' indicates that it is a private variable, demonstrating encapsulation by hiding the implementation details.
Discuss About this Question.
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.")
A:
It allows read-only access to the width property
B:
It provides write access to the width property with validation
C:
It creates a new instance of the class
D:
It exposes all internal details of the class
Answer: B
The @width.setter decorator allows write access to the 'width' property with the provided validation in the setter method.
Discuss About this Question.
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
A:
Add a single underscore prefix before 'password'
B:
Add a double underscore prefix before 'password'
C:
Use a getter method for 'password'
D:
Make 'password' a global variable
Answer: B
Adding a double underscore prefix before 'password' makes it a private variable, enforcing encapsulation within the class.
Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.