Python Programming - Objects

Exercise : Objects - General Questions
  • Objects - General Questions
16.
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?
30
31
29
None
Answer: Option
Explanation:
The celebrate_birthday method increments the age attribute by 1, so after calling john.celebrate_birthday(), the updated age will be 31.

17.
What is the purpose of the __len__ method in Python classes?
To calculate the length of an object
To create a new instance of the class
To define class attributes
To delete the class object
Answer: Option
Explanation:
The __len__ method is used to define the length of an object when the len() function is called.

18.
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()?
6
9
12
27
Answer: Option
Explanation:
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.

19.
In Python, what is the purpose of the __eq__ method in a class?
To check if two objects are equal
To create a new instance of the class
To define class attributes
To delete a specific attribute
Answer: Option
Explanation:
The __eq__ method is used to define the equality comparison between two objects when the == operator is used.

20.
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?
800
900
1000
1200
Answer: Option
Explanation:
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.