Operator Overloading
Adapted from: https://thepythonguru.com/python-operator-overloading/
You have already seen you can use + operator for adding numbers and at the
same time to concatenate strings. It is possible because + operator is overloaded by
both int class and str class. The operators are actually methods defined in respective
classes. Defining methods for operators is known as operator overloading. For e.g.:
To use + operator with custom objects you need to define a method called __add__.
Let's take an example to understand better:
1 import math
2
3 class Circle:
4
5 def __init__(self, radius):
6 self.__radius = radius
7
8 def setRadius(self, radius):
9 self.__radius = radius
10
11 def getRadius(self):
12 return self.__radius
13
14 def area(self):
15 return math.pi * self.__radius ** 2
16
17 def __add__(self, another_circle):
18 return Circle( self.__radius + another_circle.getRadius() )
19
20 c1 = Circle(4)
21 print(c1.getRadius())
22
23 c2 = Circle(5)
24 print(c2.getRadius())
25
26 c3 = c1 + c2 # This became possible because we have overloaded
27 # + operator by adding a method named __add__
28 print(c3.getRadius())
Expected Output:
4
5
9
In the above example we have added __add__() method which allows use to use the
+ operator to add two circle objects. Inside the __add__() method we are creating a
new object and returning it to the caller.
Python has many other special methods like __add__(), see the list below.
Operator Function Method Description
+ __add__(self, other) Addition
* __mul__(self, other) Multiplication
- __sub__(self, other) Subtraction
% __mod__(self, other) Remainder
/ __truediv__(self, other) Division
// __floordiv__(self, other) Floor Division
< __lt__(self, other) Less than
<= __le__(self, other) Less than or equal to
== __eq__(self, other) Equal to
!= __ne__(self, other) Not equal to
> __gt__(self, other) Greater than
>= __ge__(self, other) Greater than or equal to
[index] __getitem__(self, index) Index operator
in __contains__(self, value) Check membership
len __len__(self) The number of elements
str __str__(self) The string representation
The program below is using some of the above-mentioned methods to overload
operators.
1 import math
2
3 class Circle:
4
5 def __init__(self, radius):
6 self.__radius = radius
7
8 def setRadius(self, radius):
9 self.__radius = radius
10
11 def getRadius(self):
12 return self.__radius
13
14 def area(self):
15 return math.pi * self.__radius ** 2
16
17 def __add__(self, another_circle):
18 return Circle( self.__radius + another_circle.getRadius() )
19
20 def __gt__(self, another_circle):
21 return self.__radius > another_circle.getRadius()
22
23 def __lt__(self, another_circle):
24 return self.__radius < another_circle.getRadius()
25
26 def __str__(self):
27 return "Circle with radius " + str(self.__radius)
28
29 c1 = Circle(4)
30 print(c1.getRadius())
31
32 c2 = Circle(5)
33 print(c2.getRadius())
34
35 c3 = c1 + c2
36 print(c3.getRadius())
37
38 print(c3 > c2) # Became possible because we have added __gt__ method
39
40 print(c1 < c2) # Became possible because we have added __lt__ method
41
42 print(c3) # Became possible because we have added __str__ method
Expected Output:
4
5
9
True
True
Circle with radius 9
Instructor Notes:
1. Comparison operators must return a Boolean value.
2. __str__ method must return a string.
3. Arithmetic operators, when applicable, must return an object of the same type
as self (the left-hand operand)
4. The rules of precedence and associativity cannot be changed for any operator.
5. Operator overloading cannot be used to change the way the operators work
with built-in data types (e.g. int, float, string, lists, etc.)