Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
Python - Magic Methods and Operator Overloading
What will be the output of this code?
class Cat:
    def __repr__(self):
        return 'Cat()'
    def __str__(self):
        return 'A cat'

c = Cat()
print(c)
AA cat
BCat()
C<__main__.Cat object at 0x...>
DError
Step-by-Step Solution
Solution:
  1. Step 1: Understand print calls __str__ if available

    When printing an object, Python calls __str__ if defined, otherwise __repr__.
  2. Step 2: Check class methods

    Cat class defines both __repr__ and __str__, so print(c) calls __str__, which returns 'A cat'.
  3. Final Answer:

    A cat -> Option A
  4. Quick Check:

    print calls __str__ if present = 'A cat' [OK]
Quick Trick: print() uses __str__ if defined, else __repr__ [OK]
Common Mistakes:
  • Assuming print calls __repr__ always
  • Expecting memory address output
  • Thinking code raises error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes