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
Definition 13.12 · Operator overloading
Giving an operator such as + or > a meaning for objects of a user-defined class by defining the corresponding special method, such as __add__ or __gt__, in that class.
Python translates x + y into x.__add__(y). Special methods with double underscores on both sides are also called dunder methods or magic methods.
Expression Calls Expression Calls 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'.
Correction · Calling the special methods directly
Study material says: in §13.6 and §13.7, 2 + 5 is shown as int(2)._ _add(5), list addition as [2,3,4]._ _add_ _[5,6], string addition as 'IGNO'. _ _add_ _ 'U University.', and A + B as init.__add__(a,b).
Correct version: (2).__add__(5) (or int.__add__(2, 5)), [2, 3, 4].__add__([5, 6]) and 'IGNO'.__add__('U University'), each giving 7, [2, 3, 4, 5, 6] and 'IGNOU University'. The method name has two underscores on each side with no spaces, and the argument goes in parentheses. The class of integers is int, not init.
Why: a method call needs parentheses around its arguments; square brackets would mean indexing. All four corrected expressions were run and give the results shown. In practice you write x + y and let Python call __add__.
Intuition
An operator is like a universal “combine” button. Pressing it on two numbers adds them, on two lists joins them. When you design a new kind of object, you decide what “combine” means for it by writing __add__.
Example 13.13 Adding, comparing and printing Student marks
Goal. Make Student objects work with +, >, == and print().
Step. __add__ returns a new Student whose marks are the sums of the two operands’ marks.
Step. __gt__ and __eq__ compare total marks; __str__ gives a readable form.
Python · operator_overloading.py Copy class Student :
def __init__(self, m1, m2):
self.m1 = m1
self.m2 = m2
def __add__(self, other):
return Student(self.m1 + other.m1, self.m2 + other.m2)
def total(self):
return self.m1 + self.m2
def __gt__(self, other):
return self.total() > other.total()
def __eq__(self, other):
return self.total() == other.total()
def __str__(self):
return f "( { self.m1 } , { self.m2 } )"
s1 = Student( 52 , 73 )
s2 = Student( 56 , 97 )
s3 = s1 + s2
print ( "s1 + s2 =" , s3)
print ( "s1 wins" if s1 > s2 else "s2 wins" )
print (Student( 60 , 40 ) == Student( 50 , 50 ), s1 < s2)
Output Copy s1 + s2 = (108, 170)
s2 wins
True True
Step. Note that s1 < s2 works even though only __gt__ was defined: Python tries s1.__lt__(s2), finds it unsupported, and then uses the reflected s2.__gt__(s1).
Result. The operators now have meanings chosen for students: + adds marks subject by subject, comparisons use the totals, and print shows the marks.
Key idea
Every operator calls a special method of the left operand (x + y is x.__add__(y)); defining these dunder methods gives your own classes meaningful operators, and __str__ controls how they print.
TEE Exam note
For “explain operator overloading with an example”, give the table of operators and methods, show the TypeError for an undefined operator, and write a class (such as Student or Point) that overloads + and > and defines __str__, with its output.
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?
A a.__mult__(b)B a.__mul__(b)C a.__times__(b)D mul(a, b)
Check answer
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__?
A Python joins their attributes B It returns None C TypeError: unsupported operand type(s) for +D The objects are added as numbers
Check answer
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 Copy 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) A Point(1, 2)Point(3, 4) B (4, 6) C An error D Point(4, 6)
Check answer
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?
A __length__B __size__C __count__D __len__
Check answer
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])?
A [1, 2, 3]B [4, 5]C 6 D An error
Check answer
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.