MCS-201 · Unit 13

Classes in Python

Section 6 of 7

Block 4 · Unit 13Classes in Python8 min · Section 6 of 7

13.6Operator Overloading

Covers IGNOU MCS-201 §13.6

The same operator does different things for different types: 2 + 5 adds, [2, 3] + [4] joins lists, "IGNO" + "U" joins strings. This is possible because each operator calls a special method of the left operand’s class. By defining those methods, your own classes can use operators too.

Operators are method calls

Python translates x + y into x.__add__(y). Special methods with double underscores on both sides are also called dunder methods or magic methods.

ExpressionCallsExpressionCalls
x + yx.__add__(y)x == yx.__eq__(y)
x - yx.__sub__(y)x != yx.__ne__(y)
x * yx.__mul__(y)x < yx.__lt__(y)
x / yx.__truediv__(y)x <= yx.__le__(y)
x // yx.__floordiv__(y)x > yx.__gt__(y)
x % yx.__mod__(y)x >= yx.__ge__(y)
len(x)x.__len__()str(x), print(x)x.__str__()
repr(x)x.__repr__()x[i]x.__getitem__(i)

If a class does not define the method, the operator raises TypeError, for example TypeError: unsupported operand type(s) for +: 'Student' and 'Student'.

Key takeaways

  • Operators call dunder methods: + → __add__, > → __gt__, == → __eq__.
  • Undefined operators raise TypeError.
  • __add__ should return a new object.
  • __str__ (and __repr__) control how objects are shown.

Practice questions

Answer on paper first, then check. The explanation matters more than the letter you chose.

Question 1 · multiple choice

Which method does a * b call?

Show answer

Answer: B. a.__mul__(b)

Multiplication uses __mul__; the other names do not exist.

Question 2 · multiple choice

What happens when you use + on two objects of a class without __add__?

Show answer

Answer: C. TypeError: unsupported operand type(s) for +

Python cannot guess what addition means for an arbitrary class.

Question 3 · multiple choice

What does this program print?

Python · quiz_point.py
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)
    def __str__(self):
        return f"Point({self.x}, {self.y})"

p = Point(1, 2) + Point(3, 4)
print(p)
Show answer

Answer: D. Point(4, 6)

__add__ returns a new point (4, 6), and print uses __str__.

Question 4 · multiple choice

Which method should be defined so that len(obj) works?

Show answer

Answer: D. __len__

len(obj) calls obj.__len__(), which must return a non-negative integer.

Question 5 · multiple choice

What is [1, 2].__add__([3])?

Show answer

Answer: A. [1, 2, 3]

This is exactly what [1, 2] + [3] does: list concatenation.

Question 6 · short answer

Write a class Money holding rupees and paise that overloads + so that paise carry over into rupees, and give the output for ₹10.75 + ₹5.50.

Show worked answer

class Money: with def __init__(self, rupees, paise): self.rupees = rupees + paise // 100; self.paise = paise % 100, def __add__(self, other): return Money(self.rupees + other.rupees, self.paise + other.paise) and def __str__(self): return f"Rs {self.rupees}.{self.paise:02d}". Then print(Money(10, 75) + Money(5, 50)): rupees 15, paise 125, which the constructor normalises to 16 rupees and 25 paise, printing Rs 16.25.

↑ ↓ move↵ openTab switch type