Python Operator Overloading
New Course Coming Soon:
Get Really Good at Git
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:
__eq__()
to check for equality__lt__()
to check if an object should be considered lower than another with the<
operator__le__()
for lower or equal (<=
)__ge__()
for greater or equal (>=
)__ne__()
for not equal (!=
)
Then you have methods to interoperate with arithmetic operations:
__add__()
respond to the+
operator__sub__()
respond to the–
operator__mul__()
respond to the*
operator__truediv__()
respond to the/
operator__floordiv__()
respond to the//
operator__mod__()
respond to the%
operator__pow__()
respond to the**
operator__rshift__()
respond to the>>
operator__lshift__()
respond to the<<
operator__and__()
respond to the&
operator__or__()
respond to the|
operator__xor__()
respond to the^
operator
There are a few more methods to work with other operators, but you got the idea.
Are you intimidated by Git? Can’t figure out merge vs
rebase? Are you afraid of screwing up something any time
you have to do something in Git? Do you rely on ChatGPT
or random people’s answer on StackOverflow to fix your
problems? Your coworkers are tired of explaining Git to
you all the time? Git is something we all need to use,
but few of us really master it. I created this course to
improve your Git (and GitHub) knowledge at a radical
level. A course that helps you feel less frustrated with
Git. Launching Summer 2024. Join the waiting list!
→ Get my Python Handbook
→ Get my Python Handbook
Here is how can I help you:
- COURSES where I teach everything I know
- THE VALLEY OF CODE your web development manual
- BOOTCAMP 2024 cohort in progress, next edition in 2025
- BOOKS 16 coding ebooks you can download for free on JS Python C PHP and lots more
- SOLO LAB everything I know about running a lifestyle business as a solopreneur
- Interesting links collection
- Follow me on X