Bird
Raised Fist0

What will be the output of this code?

medium📝 Predict Output Q5 of Q15
Python - Methods and Behavior Definition
What will be the output of this code?
class Tally:
    def __init__(self):
        self.total = 0
    def add(self):
        self.total += 2
    def get_total(self):
        return self.total

t = Tally()
t.add()
t.add()
print(t.get_total())
A2
BError
C0
D4
Step-by-Step Solution
Solution:
  1. Step 1: Initial value of total is 0

    The constructor sets self.total = 0.
  2. Step 2: Each call to add() increases total by 2

    Calling add() twice adds 2 + 2 = 4.
  3. Step 3: get_total() returns current total

    Returns 4 after two increments.
  4. Final Answer:

    4 -> Option D
  5. Quick Check:

    Instance variables update correctly with method calls [OK]
Quick Trick: Instance variables update with each method call [OK]
Common Mistakes:
MISTAKES
  • Assuming add increments by 1 instead of 2
  • Not calling methods with parentheses
  • Confusing class and instance variables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes