This quiz tests your understanding of Python classes, specifically how attributes can be dynamically added to instances of a class outside the class definition.
Contents
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:
- Class Definition: The class
Productis defined with no attributes or methods. - Creating Instances: A list
prodsis initialized, and three instances ofProductare created in a loop. For each instance, thepriceattribute is dynamically set asi * 6, whereiis the loop index (1, 2, 3). - Appending to List: Each
Productinstance with itspriceis appended to the listprods. - Filtering and Printing: A second loop iterates over the list
prods, printing thepriceof eachProductinstance that has apricegreater than 10.
Expected Output:
- The first
Productinstance has apriceof 6 (1 * 6) and does not meet the condition (price > 10), so it is not printed. - The second instance has a
priceof 12 (2 * 6) and is printed. - The third instance has a
priceof 18 (3 * 6) and is printed.
Thus, the output will be:
12
18Question 25: Understanding Dynamic Attributes in Python Classes