Exercise: Encapsulation
Questions for: Encapsulation
Which access specifier in Python is used to indicate that a variable or method should be accessible from anywhere, both within and outside the class?
A:
Public
B:
Private
C:
Protected
D:
Global
Answer: A
Public access specifier in Python is used to indicate that a variable or method should be accessible from anywhere, both within and outside the class.
In Python, what is a getter method used for in the context of encapsulation?
A:
To set the value of a private variable
B:
To delete a private variable
C:
To retrieve the value of a private variable
D:
To define a new private variable
Answer: C
In encapsulation, a getter method is used to retrieve the value of a private variable.
Discuss About this Question.
What is the purpose of the single underscore prefix in Python, as in
_variable?
A:
To indicate a protected variable
B:
To indicate a private variable
C:
To indicate a global variable
D:
To indicate a constant variable
Answer: A
The single underscore prefix in Python, as in
_variable, is used to indicate a protected variable.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):
self.__balance += amount
def withdraw(self, amount):
if amount <= self.__balance:
self.__balance -= amount
return True
else:
return False
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 double underscore prefix (
__) in the variable __balance indicates that it is a private variable, demonstrating encapsulation by hiding the implementation details.Discuss About this Question.
Which access specifier in Python is used to indicate that a variable or method should be accessible by subclasses?
A:
Public
B:
Private
C:
Protected
D:
Global
Answer: C
Protected access specifier in Python is denoted by a single underscore (
_), and it indicates that the variable or method should be accessible by subclasses.Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.