PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Medium

Question 38

Suppose you have the following class:



You've created two instances of this class:



What is the result of the following operation?



  • 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:

  1. Class Definition:

    • The ProductionLine class has an __init__ method that initializes the capacity attribute.

    • 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 of ProductionLine. This method returns a new ProductionLine instance with a capacity that is calculated as the sum of the two capacity attributes minus 50.

  2. Instance Creation:

    • prod1 = ProductionLine(100) creates an instance of ProductionLine with a capacity of 100.

    • prod2 = ProductionLine(200) creates another instance with a capacity of 200.

  3. Addition Operation (prod1 + prod2):

    • When you perform prod1 + prod2, Python calls the __add__ method.

    • Inside the __add__ method:

      • self.capacity refers to the capacity of prod1, which is 100.

      • other.capacity refers to the capacity of prod2, which is 200.

      • The method calculates the new capacity as 100 + 200 - 50, which equals 250.

    • A new ProductionLine instance is returned with this calculated capacity.

  4. Result:

    • The result is a new ProductionLine instance with capacity=250.

    • When you print or inspect this result, the __repr__ method is called, which returns the string ProductionLine(capacity=250).

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need