Bird
0
0

Find the error in this code that tries to overload the multiplication operator (*) for a class:

medium📝 Debug Q14 of 15
Python - Magic Methods and Operator Overloading
Find the error in this code that tries to overload the multiplication operator (*) for a class:
class Multiplier:
    def __init__(self, num):
        self.num = num
    def __mul__(self, other):
        return self.num * other.num

m1 = Multiplier(3)
m2 = Multiplier(4)
print(m1 * m2)
AThe __mul__ method should return a Multiplier object, not an int
BThe __init__ method is missing a return statement
CThe print statement should use str(m1 * m2)
DThe __mul__ method should be named __multiply__
Step-by-Step Solution
Solution:
  1. Step 1: Check __mul__ return type

    __mul__ returns an int (self.num * other.num), but operator overloading usually returns an object of the class.
  2. Step 2: Understand why returning int is a problem

    Returning int means further chained operations on Multiplier objects will fail or behave unexpectedly.
  3. Final Answer:

    The __mul__ method should return a Multiplier object, not an int -> Option A
  4. Quick Check:

    __mul__ must return class instance for chaining [OK]
Quick Trick: Return class instance in operator methods, not raw values [OK]
Common Mistakes:
  • Returning raw int instead of class instance
  • Thinking __init__ needs return
  • Misnaming __mul__ method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes