Skip to ContentGo to accessibility pageKeyboard shortcuts menu
OpenStax Logo
Introduction to Python Programming

11.4 Overloading operators

Introduction to Python Programming11.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

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

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

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 permission.

Want to cite, share, or modify this book? This book uses the Creative Commons Attribution License and you must attribute OpenStax.

Attribution information
  • If you are redistributing all or part of this book in a 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 digital format, then you must 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

© Feb 26, 2024 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution License . The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo are not subject to the Creative Commons license and may not be reproduced without the prior and express written consent of Rice University.