Python Programming - Objects
Exercise : Objects - General Questions
- Objects - General Questions
11.
Consider the following Python code:
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def calculate_perimeter(self):
return 2 * (self.length + self.width)
If you create an instance of the `Rectangle` class called `my_rectangle` with length 4 and width 6, what will be the result of calling my_rectangle.calculate_perimeter()
?
Answer: Option
Explanation:
The
calculate_perimeter
method calculates the perimeter of the rectangle using the formula 2 * (length + width). For the given instance, it would be 2 * (4 + 6) = 24.
12.
What is the primary purpose of the
__str__
method in Python classes?
Answer: Option
Explanation:
The
__str__
method is used to define the string representation of an object. It is automatically called when the str()
function is invoked on the object.
13.
Consider the following Python code:
class BankAccount:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self.balance
If you create an instance of the `BankAccount` class called my_account
with an initial balance of 100 and then call my_account.deposit(50)
, what will be the updated balance?
Answer: Option
Explanation:
The
deposit
method adds the specified amount to the balance. In this case, it would be 100 + 50 = 150.
14.
In Python, what is the purpose of the
__del__
method in a class?
Answer: Option
Explanation:
The
__del__
method is called when an object is about to be destroyed. It can be used to perform cleanup operations before the object is deleted.
15.
Consider the following Python code:
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def to_fahrenheit(self):
return (self.celsius * 9/5) + 32
If you create an instance of the `Temperature` class called my_temp
with a Celsius value of 25 and then call my_temp.to_fahrenheit()
, what will be the result?
Answer: Option
Explanation:
The
to_fahrenheit
method converts Celsius to Fahrenheit using the formula (Celsius * 9/5) + 32. For the given instance, it would be (25 * 9/5) + 32 = 77.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers