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
Product
is defined with no attributes or methods. - Creating Instances: A list
prods
is initialized, and three instances ofProduct
are created in a loop. For each instance, theprice
attribute is dynamically set asi * 6
, wherei
is the loop index (1, 2, 3). - Appending to List: Each
Product
instance with itsprice
is appended to the listprods
. - Filtering and Printing: A second loop iterates over the list
prods
, printing theprice
of eachProduct
instance that has aprice
greater than 10.
Expected Output:
- The first
Product
instance has aprice
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
Question 25: Understanding Dynamic Attributes in Python Classes