Bird
Raised Fist0

Given this code, what will be the output?

hard🚀 Application Q9 of Q15
Python - Methods and Behavior Definition
Given this code, what will be the output?
class Item:
    def __init__(self, name, quantity):
        self.name = name
        self.quantity = quantity
    def restock(self, amount):
        self.quantity += amount

item = Item("Pen", 10)
item.restock(5)
item.quantity = 3
print(item.quantity)
A5
B15
C10
D3
Step-by-Step Solution
Solution:
  1. Step 1: Initial quantity and restock

    Item starts with quantity 10, restock adds 5, total 15.
  2. Step 2: Direct attribute assignment

    Then quantity is set directly to 3, overwriting previous value.
  3. Step 3: Print final quantity

    Print outputs 3, the last assigned value.
  4. Final Answer:

    3 -> Option D
  5. Quick Check:

    Last assignment to attribute determines final state [OK]
Quick Trick: Direct assignment overwrites previous attribute changes [OK]
Common Mistakes:
MISTAKES
  • Ignoring direct assignment after method call
  • Assuming restock value remains
  • Confusing initial value with final

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes