Exercise: Encapsulation
Questions for: Encapsulation
Consider the following Python code:
class Customer:
def __init__(self, name, email):
self._name = name
self._email = email
def display_info(self):
return f"Name: {self._name}, Email: {self._email}"
What concept of encapsulation is demonstrated in this code?
A:
Public access specifier
B:
Private access specifier
C:
Protected access specifier
D:
Global variable
Answer: B
The single underscore prefix (
_) in the variables _name and _email indicates that they are private variables, demonstrating encapsulation by hiding the implementation details.
What is the purpose of using encapsulation?
A:
To increase code complexity
B:
To combine data and methods into a single unit
C:
To expose all implementation details of an object
D:
To make all variables public for easy access
Answer: B
The purpose of using encapsulation in Python is to combine data and methods into a single unit, promoting modularity.
Discuss About this Question.
In Python, what is the purpose of the
__str__() method in a class?
A:
To create a new instance of a class
B:
To define a private variable
C:
To provide a string representation of the object
D:
To access a global variable
Answer: C
The
__str__() method in Python is used to provide a string representation of the object when the str() function is called.Discuss About this Question.
Which of the following is a benefit of encapsulation?
A:
Increased code complexity
B:
Improved code reusability
C:
Reduced data security
D:
Unrestricted access to internal details
Answer: B
Encapsulation in Python promotes improved code reusability by encapsulating data and methods into a single unit.
Discuss About this Question.
Consider the following Python code:
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def get_balance(self):
return self.__balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
What is the encapsulation concept demonstrated in this code?
A:
Public access specifier
B:
Private access specifier
C:
Protected access specifier
D:
Global variable
Answer: B
The double underscore prefix in the variable
__balance indicates that it is a private variable, demonstrating the encapsulation concept of private access.Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.