PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Medium
Question 38
Suppose you have the following class:
- class ProductionLine:
- def __init__(self, capacity):
- self.capacity = capacity
- def __repr__(self):
- return f'ProductionLine(capacity={self.capacity})'
- def __add__(self, other):
- return ProductionLine(self.capacity + other.capacity - 50)
You've created two instances of this class:
- prod1 = ProductionLine(100)
- prod2 = ProductionLine(200)
What is the result of the following operation?
- prod1 + prod2
-
A
300 -
B
250 -
C
ProductionLine(capacity=300) -
D
ProductionLine(capacity=250)
Reveal correct answer
Correct answer: D
A.
This is incorrect because the subtraction of 50 in the __add__ method results in a capacity of 250, not 300.
B.
This is incorrect because the result is not just the integer 250; it is a ProductionLine object with a capacity of 250.
C.
This is incorrect because the __add__ method subtracts 50 from the sum of the capacities, resulting in 250, not 300.
D.
Let's break down the code step by step:
Class Definition:
The
ProductionLineclass has an__init__method that initializes thecapacityattribute.The
__repr__method provides a string representation of the object, which is useful for debugging or printing the object.The
__add__method is overridden to allow the+operator to be used between two instances ofProductionLine. This method returns a newProductionLineinstance with a capacity that is calculated as the sum of the twocapacityattributes minus 50.
Instance Creation:
prod1 = ProductionLine(100)creates an instance ofProductionLinewith a capacity of 100.prod2 = ProductionLine(200)creates another instance with a capacity of 200.
Addition Operation (
prod1 + prod2):When you perform
prod1 + prod2, Python calls the__add__method.Inside the
__add__method:self.capacityrefers to the capacity ofprod1, which is 100.other.capacityrefers to the capacity ofprod2, which is 200.The method calculates the new capacity as
100 + 200 - 50, which equals250.
A new
ProductionLineinstance is returned with this calculated capacity.
Result:
The result is a new
ProductionLineinstance withcapacity=250.When you print or inspect this result, the
__repr__method is called, which returns the stringProductionLine(capacity=250).
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
