Skip to content

Python Operator Overloading

Operator overloading is an advanced technique we can use to make classes comparable and to make them work with Python operators.

Let’s take a class Dog:

class Dog:
    # the Dog class
    def __init__(self, name, age):
        self.name = name
        self.age = age

Let’s create 2 Dog objects:

roger = Dog('Roger', 8)
syd = Dog('Syd', 7)

We can use operator overloading to add a way to compare those 2 objects, based on the age property:

class Dog:
    # the Dog class
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __gt__(self, other):
        return True if self.age > other.age else False

Now if you try running print(roger > syd) you will get the result True.

In the same way we defined __gt__() (which means greater than), we can define the following methods:

Then you have methods to interoperate with arithmetic operations:

There are a few more methods to work with other operators, but you got the idea.


→ Get my Python Handbook
→ Get my Python Handbook

→ I wrote 17 books to help you become a better developer:

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook
...download them all now!

Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list