Skip to ContentGo to accessibility page
Introduction to Python Programming

11.4 Overloading operators

Introduction to Python Programming11.4 Overloading operators

11.4 Overloading operators

Learning objectives

By the end of this section you should be able to

  • Identify magic methods and describe their purpose.
  • Develop overloaded arithmetic and comparison operators for user-defined classes.

Magic methods and customizing

Magic methods are special methods that perform actions for users, typically out of view of users. Magic methods are also called dunder methods, since the methods must start and end with double underscores (__). Ex: __init__() is a magic method used alongside __new__() to create a new instance and initialize attributes with a simple line like eng = Engineer(). A programmer can explicitly define a magic method in a user-defined class to customize the method's behavior.

Checkpoint

Customizing __str__() in a user-defined class, Engineer

Customizing _str_() in a user-defined class, Engineer; ch 11, video 8

Concepts in Practice

Magic methods

1.
Which of the following is a magic method?
  1. add()
  2. _add_()
  3. __add__()
2.
Why are magic methods special?
  1. can't be called by the user
  2. perform internal actions
  3. have fixed definitions
3.
Consider the example above, and identify the magic method(s) in the updated program.
  1. __init__()
  2. __str__()
  3. __init__(), __str__()

Overloading arithmetic operators

Operator overloading refers to customizing the function of a built-in operator. Arithmetic operators are commonly overloaded to allow for easy changes to instances of user-defined classes.

Checkpoint

Overloading __add__() for a user-defined class, Account

Overloading _add_() for a user-defined class, Account; ch 11, video 9

Arithmetic operator (Operation) Magic method
+ (Addition)
__add__(self, other)
- (Subtraction)
__sub__(self, other)
* (Multiplication)
__mul__(self, other)
/ (Division)
__truediv__(self, other)
% (Modulo)
__mod__(self, other)
** (Power)
__pow__(self, other)
Table 11.1 Arithmetic operators and magic methods.

Concepts in Practice

Arithmetic operator overloading

4.
A programmer explicitly defining the modulo operator for their user-defined class is ___________ the operator.
  1. overloading
  2. rewriting
  3. implementing
5.
Given the code below, which argument maps to the parameter other in the call to Account.__add__()?
acct_a = Account("Ashe", 6492)
acct_b = Account("Bevins", 5210)

acct_ab = acct_a + acct_b
  1. acct_a
  2. acct_b
  3. acct_ab
6.
Which __sub__() definition overloads the - operator for the code below to work?
class Pair:
  def __init__(self, x=0, y=0):
    self.x = x
    self.y = y
  # Define __sub__()

p1 = Pair(10, 2)
p2 = Pair(8, 4)
p3 = p1 - p2
print(p3.x, p3.y)
  1.   def __sub__(self):
        return Pair(self.x - other.x, self.y - other.y)
    
  2.   def __sub__(self, other):
        return self.x - other.x, self.y - other.y
    
  3.   def __sub__(self, other):
        return Pair(self.x - other.x, self.y - other.y)
    

Overloading comparison operators

Comparison operators can also be overloaded like arithmetic operators.

Comparison operator (Operation) Magic method
< (Less than)
__lt__(self, other)
> (Greater than)
__gt__(self, other)
<= (Less than or equal to)
__le__(self, other)
>= (Greater than or equal to)
__ge__(self, other)
== (Equal)
__eq__(self, other)
!= (Not equal)
__ne__(self, other)
Table 11.2 Comparison operators and magic methods.

Example 11.2

Overloading comparison operators for the Account class

Code Output
class Account:
  def __init__(self, name="", amount=0):
    self.name = name
    self.amount = amount

  def __str__(self):
    return f"{self.name}: ${self.amount}"

  def __lt__(self, other):
    return self.amount < other.amount

  def __gt__(self, other):
    return self.amount > other.amount

  def __eq__(self, other):
    return self.amount == other.amount

acct_a = Account("Ashe", 6492)
acct_b = Account("Bevins", 5210)

print(acct_a < acct_b)
print(acct_a > acct_b)
acct_a.amount = 5210
print(acct_a == acct_b)
False

True

True
Table 11.3

Concepts in Practice

Comparison operator overloading

Consider the example above.

7.
How many operators are overloaded?
  1. 3
  2. 4
  3. 5
8.
Which code appropriately overloads the <= operator?
  1.   def __le__(other):
        return self.amount <= other.amount
    
  2.   def __le__(self, other):
        return self.amount <= other.amount
    
  3.   def __le__(self, other):
        return other.amount <= self.amount
    
9.
Which type of value does __gt__() return?
  1. account instance
  2. Boolean
  3. integer

Try It

Combining exercise logs

The ExerciseLog class has two instance attributes: e_type, the type of exercise, and duration, the time spent exercising.

Overload the + operator to combine two ExerciseLogs such that:

  • If the exercise types are different, combine them with " and " in between. Else, use the same type and don't duplicate.
  • Add durations together.

Given input:

    walk
    5
    run
    30

The output is:

    walk and run: 35 minutes

Try It

Expanding the Account class

Using isinstance() allows the programmer to define different behaviors depending on an object's type. The first parameter is the object, and the second parameter is the type or class. Ex: isinstance(my_var, int) returns True if my_var is an integer.

Expand the existing Account example so that the addition operator can also be used to add an integer value to an Account's amount attribute.

Citation/Attribution
Reuse and redistribution of this content in digital or print format:
  • This book may not be used in the training of large language models or otherwise be ingested into large language models or generative AI offerings without OpenStax's prior written permission.
  • This book uses the Creative Commons Attribution-NonCommercial-ShareAlike License, which means that you can reuse and modify the material only for noncommercial purposes, must attribute OpenStax, and must distribute any derivative works under the same license.
  • Any commercial printing of this textbook, including using a local or custom printer, must be approved by OpenStax, and proper citation provided.
  • OpenStax-copyrighted images, activities, assessments, and similar components of this book are subject to the same licensing – CC-BY-NC-SA. They can be used for noncommercial purposes with attribution. Commercial use requires permission.
  • Permission requests: Anyone who intends to incorporate this content (including text, images, and other components) into large language models, use it in AI offerings, use it commercially (including in print), and/or has questions about another use case is welcome to complete our reuse request form.
Attribution information
  • If you are redistributing all or part of this book in a noncommercial print format, then you must include on every physical page the following attribution:

    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction

  • If you are redistributing all or part of this book in a noncommercial digital format, then for every page that includes OpenStax content, you must license the derivative work under the same CC-BY-NC-SA license as the original, and include on every digital page view the following attribution:

    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction

Citation information

The information below includes the information needed to generate citations in most major styles (APA, MLA, etc.); you must reformat and organize the information as needed to fit the requirements of the style. Use the information below to generate a citation. We recommend using a citation tool such as this one.

© Apr 23, 2026 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike License. The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo, and Rice University name, and Rice University logo trademarks, or wordmarks are not subject to the Creative Commons license and may not be reproduced without the prior and express written consent of Rice University.

This book utilizes the OpenStax Python Code Runner. The code runner is developed by Wiley and is All Rights Reserved.