Python Programming - Encapsulation
Exercise : Encapsulation - General Questions
- Encapsulation - General Questions
61.
Consider the following Python code:
class Person:
def __init__(self, name, __age):
self.name = name
self.__age = __age
def get_age(self):
return self.__age
What is the purpose of the get_age() method?
Answer: Option
Explanation:
The get_age() method is designed to retrieve the private variable __age, demonstrating encapsulation by providing controlled access.
62.
How can encapsulation be achieved in Python to provide read-only access to a variable?
class Example:
def __init__(self):
self.__value = 42
Answer: Option
Explanation:
To provide read-only access to a variable, a getter method can be created to retrieve the value.
63.
What is the advantage of encapsulating a class attribute with a double underscore prefix, such as __count?
class MyClass:
__count = 0
def increment_count(self):
MyClass.__count += 1
Answer: Option
Explanation:
Encapsulation with a double underscore prefix improves code maintainability by hiding the implementation details of the class attribute __count.
64.
What is the purpose of the following Python code?
class TemperatureConverter:
def __init__(self, celsius):
self._celsius = celsius
@property
def fahrenheit(self):
return self._celsius * 9/5 + 32
Answer: Option
Explanation:
The @property decorator is used to create a read-only property 'fahrenheit' that calculates the temperature in Fahrenheit based on the stored Celsius value.
65.
Consider the following Python class:
class BankAccount:
def __init__(self, balance):
self._balance = balance
@property
def balance(self):
return self._balance
What does the @property decorator do in this code?
Answer: Option
Explanation:
The @property decorator is used to create a read-only property 'balance', providing controlled access to the private variable '_balance'.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers