Bird
Raised Fist0

Identify the error in this code snippet:

medium📝 Debug Q6 of Q15
Python - Magic Methods and Operator Overloading
Identify the error in this code snippet:
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2)
AIncorrect __add__ method signature
BMissing __str__ method causes print to show object address
CCannot add two Vector objects
DMissing __init__ method
Step-by-Step Solution
Solution:
  1. Step 1: Check class methods

    The class has __init__ and __add__ correctly defined, so addition works.
  2. Step 2: Understand print behavior

    Without a __str__ method, printing the result shows the default object memory address.
  3. Final Answer:

    Missing __str__ method causes print to show object address -> Option B
  4. Quick Check:

    No __str__ = default print output [OK]
Quick Trick: Add __str__ to print readable output [OK]
Common Mistakes:
MISTAKES
  • Thinking __add__ signature is wrong
  • Assuming addition is not supported
  • Forgetting print calls __str__

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes