Bird
Raised Fist0
Pythonprogramming~20 mins

Arithmetic operator overloading in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Operator Overloading Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of adding two custom objects with overloaded + operator

Consider the following Python class that overloads the + operator. What will be the output of the code below?

Python
class Number:
    def __init__(self, value):
        self.value = value
    def __add__(self, other):
        return Number(self.value + other.value)
    def __str__(self):
        return str(self.value)

n1 = Number(5)
n2 = Number(10)
result = n1 + n2
print(result)
A15
BNumber object at some memory address
CTypeError
D510
Attempts:
2 left
💡 Hint

Look at how the __add__ method returns a new Number object and how __str__ controls printing.

Predict Output
intermediate
2:00remaining
Output of subtracting custom objects with overloaded - operator

What is the output of this code that overloads the - operator?

Python
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __sub__(self, other):
        return Point(self.x - other.x, self.y - other.y)
    def __repr__(self):
        return f"Point({self.x}, {self.y})"

p1 = Point(10, 5)
p2 = Point(3, 2)
print(p1 - p2)
APoint(7, 3)
BPoint(13, 7)
CTypeError
DNone
Attempts:
2 left
💡 Hint

Check how the __sub__ method calculates the difference of coordinates.

Predict Output
advanced
2:00remaining
Output of multiplying custom objects with overloaded * operator returning int

What will this code print? The * operator is overloaded to return an integer.

Python
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __mul__(self, other):
        return self.x * other.x + self.y * other.y

v1 = Vector(2, 3)
v2 = Vector(4, 5)
print(v1 * v2)
ANone
BVector(8, 15)
CTypeError
D23
Attempts:
2 left
💡 Hint

The * operator here calculates the dot product of two vectors.

Predict Output
advanced
2:00remaining
Output of in-place addition with overloaded __iadd__ method

What is the output of this code that overloads the += operator?

Python
class Counter:
    def __init__(self, count=0):
        self.count = count
    def __iadd__(self, other):
        self.count += other.count
        return self
    def __str__(self):
        return str(self.count)

c1 = Counter(5)
c2 = Counter(10)
c1 += c2
print(c1)
ACounter object at some memory address
B15
CTypeError
D10
Attempts:
2 left
💡 Hint

The __iadd__ method modifies the object in place and returns it.

🧠 Conceptual
expert
2:00remaining
Behavior of unsupported arithmetic operator overloading

Given this class that only overloads __add__, what happens if you try to subtract two objects?

class MyNum:
    def __init__(self, val):
        self.val = val
    def __add__(self, other):
        return MyNum(self.val + other.val)

x = MyNum(5)
y = MyNum(3)
z = x - y
AReturns None
BReturns MyNum(2)
CRaises TypeError: unsupported operand type(s) for -: 'MyNum' and 'MyNum'
DRaises AttributeError
Attempts:
2 left
💡 Hint

Check what happens if an operator method is not defined for a class.

Practice

(1/5)
1. What does arithmetic operator overloading allow you to do in Python?
easy
A. Define how operators like +, -, * work for your custom objects
B. Change the behavior of built-in data types like int and str
C. Create new arithmetic operators not available in Python
D. Automatically optimize arithmetic operations for speed

Solution

  1. Step 1: Understand operator overloading concept

    Operator overloading lets you tell Python how to use operators like + or * with your own objects.
  2. Step 2: Identify what can be customized

    You can define special methods like __add__ to customize + for your class instances.
  3. Final Answer:

    Define how operators like +, -, * work for your custom objects -> Option A
  4. Quick Check:

    Operator overloading = custom operator behavior [OK]
Hint: Think: 'How do I make + work for my objects?' [OK]
Common Mistakes:
  • Confusing operator overloading with creating new operators
  • Thinking it changes built-in types behavior
  • Assuming it improves performance automatically
2. Which special method should you define to overload the addition operator (+) in a Python class?
easy
A. __append__
B. __plus__
C. __sum__
D. __add__

Solution

  1. Step 1: Recall Python special method names for operators

    Python uses __add__ to overload the + operator in classes.
  2. Step 2: Check other options

    __plus__, __sum__, and __append__ are not valid special methods for + operator.
  3. Final Answer:

    __add__ -> Option D
  4. Quick Check:

    + operator method = __add__ [OK]
Hint: Remember: add = __add__, subtract = __sub__ [OK]
Common Mistakes:
  • Using __plus__ instead of __add__
  • Confusing __sum__ with sum() function
  • Using __append__ which is for lists
3. What will be the output of this code?
class Number:
    def __init__(self, value):
        self.value = value
    def __add__(self, other):
        return Number(self.value + other.value)
    def __str__(self):
        return str(self.value)

n1 = Number(5)
n2 = Number(10)
print(n1 + n2)
medium
A. TypeError
B. Number object at some memory address
C. 15
D. 5 10

Solution

  1. Step 1: Understand __add__ method behavior

    Adding n1 + n2 calls __add__, which returns a new Number with value 5 + 10 = 15.
  2. Step 2: Understand __str__ method effect on print

    print calls __str__ on the result, which returns '15' as string.
  3. Final Answer:

    15 -> Option C
  4. Quick Check:

    Custom + returns Number(15), printed as '15' [OK]
Hint: Check __add__ return and __str__ print output [OK]
Common Mistakes:
  • Expecting print to show object memory address
  • Forgetting __str__ method for printing
  • Thinking it raises TypeError without __add__
4. 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)
medium
A. The __mul__ method should return a Multiplier object, not an int
B. The __init__ method is missing a return statement
C. The print statement should use str(m1 * m2)
D. The __mul__ method should be named __multiply__

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]
Hint: 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
5. You want to create a class Vector that supports adding vectors and multiplying by a number. Which methods should you define to support v1 + v2 and v1 * 3 where v1 and v2 are Vector objects?
hard
A. __add__ for vector + vector, __rmul__ for number * vector
B. __add__ for vector + vector, __mul__ for vector * number
C. __add__ for vector + vector, __mul__ for number * vector
D. __radd__ for vector + vector, __mul__ for vector * number

Solution

  1. Step 1: Identify method for vector + vector

    __add__ handles adding two Vector objects like v1 + v2.
  2. Step 2: Identify method for vector * number

    __mul__ handles multiplying Vector by a number like v1 * 3.
  3. Final Answer:

    __add__ for vector + vector, __mul__ for vector * number -> Option B
  4. Quick Check:

    Use __add__ and __mul__ for these operations [OK]
Hint: Use __add__ for +, __mul__ for * with your class [OK]
Common Mistakes:
  • Confusing __rmul__ with __mul__
  • Using __radd__ instead of __add__ for vector + vector
  • Assuming number * vector uses __mul__ (it uses __rmul__)