Question 25: Understanding Dynamic Attributes in Python Classes

This quiz tests your understanding of Python classes, specifically how attributes can be dynamically added to instances of a class outside the class definition.

Question: Dynamic Attributes in Python Classes

What will be the output of this code??

class Product:
    pass
prods = []

for i in range(1, 4):
    obj = Product()
    obj.price = i * 6
    prods.append(obj)

for prod in prods:
    if prod.price > 10:
        print(prod.price)















Answer: C

Explanation:

Here’s a step-by-step breakdown:

  1. Class Definition: The class Product is defined with no attributes or methods.
  2. Creating Instances: A list prods is initialized, and three instances of Product are created in a loop. For each instance, the price attribute is dynamically set as i * 6, where i is the loop index (1, 2, 3).
  3. Appending to List: Each Product instance with its price is appended to the list prods.
  4. Filtering and Printing: A second loop iterates over the list prods, printing the price of each Product instance that has a price greater than 10.

Expected Output:

  • The first Product instance has a price of 6 (1 * 6) and does not meet the condition (price > 10), so it is not printed.
  • The second instance has a price of 12 (2 * 6) and is printed.
  • The third instance has a price of 18 (3 * 6) and is printed.

Thus, the output will be:

12
18

Leave a Reply