Exercise: Objects

Questions for: Objects

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?
A:
32
B:
77
C:
25
D:
57.2
Answer: B
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.
In Python, what is the purpose of the __del__ method in a class?
A:
To create a new instance of the class
B:
To destroy the class object
C:
To define class attributes
D:
To delete a specific attribute
Answer: B
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.
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?
A:
150
B:
100
C:
50
D:
None
Answer: A
The deposit method adds the specified amount to the balance. In this case, it would be 100 + 50 = 150.
What is the primary purpose of the __str__ method in Python classes?
A:
To create a string representation of the object
B:
To compare objects for equality
C:
To initialize the object's attributes
D:
To perform object serialization
Answer: A
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.
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()?
A:
10
B:
20
C:
24
D:
30
Answer: B
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) = 20.
Ad Slot (Above Pagination)
Quiz