Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q5 of 15
Python - Magic Methods and Operator Overloading
What will be the output of this code?
class Counter:
    def __init__(self, count):
        self.count = count
    def __add__(self, other):
        return Counter(self.count + other.count)
    def __str__(self):
        return str(self.count)
c1 = Counter(3)
c2 = Counter(4)
c3 = c1 + c2
print(c3)
ATypeError
BCounter object
C7
D34
Step-by-Step Solution
Solution:
  1. Step 1: Understand __add__ and __str__ methods

    __add__ returns a new Counter with sum of counts; __str__ returns count as string.
  2. Step 2: Trace the addition and print

    c1 + c2 creates Counter(7), print calls __str__ which returns '7'.
  3. Final Answer:

    7 -> Option C
  4. Quick Check:

    Adding objects uses __add__, printing uses __str__ = 7 [OK]
Quick Trick: Define __add__ to add objects, __str__ to print nicely [OK]
Common Mistakes:
  • Expecting print to show object memory address
  • Getting TypeError due to missing __add__
  • Concatenating counts as strings instead of adding

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes