Exercise: Objects

Questions for: Objects

Consider the following Python code:
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def apply_discount(self, discount_percentage):
        discounted_price = self.price * (1 - discount_percentage / 100)
        return discounted_price
If you create an instance of the `Product` class called laptop with a price of 1000 and then call laptop.apply_discount(20), what will be the discounted price?
A:
800
B:
900
C:
1000
D:
1200
Answer: A
The apply_discount method calculates the discounted price based on the given discount percentage. For the given instance, it would be 1000 * (1 - 20/100) = 800.
In Python, what is the purpose of the __eq__ method in a class?
A:
To check if two objects are equal
B:
To create a new instance of the class
C:
To define class attributes
D:
To delete a specific attribute
Answer: A
The __eq__ method is used to define the equality comparison between two objects when the == operator is used.
Consider the following Python code:
class Square:
    def __init__(self, side_length):
        self.side_length = side_length

    def calculate_area(self):
        return self.side_length ** 2
If you create an instance of the `Square` class called small_square with a side length of 3, what will be the result of calling small_square.calculate_area()?
A:
6
B:
9
C:
12
D:
27
Answer: B
The calculate_area method calculates the area of the square using the formula side_length ** 2. For the given instance, it would be 3 ** 2 = 9.
What is the purpose of the __len__ method in Python classes?
A:
To calculate the length of an object
B:
To create a new instance of the class
C:
To define class attributes
D:
To delete the class object
Answer: A
The __len__ method is used to define the length of an object when the len() function is called.
Consider the following Python code:
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def celebrate_birthday(self):
        self.age += 1
If you create an instance of the `Person` class called john with age 30 and then call john.celebrate_birthday(), what will be the updated age?
A:
30
B:
31
C:
29
D:
None
Answer: B
The celebrate_birthday method increments the age attribute by 1, so after calling john.celebrate_birthday(), the updated age will be 31.
Ad Slot (Above Pagination)
Quiz