Overloading Operators in Python

According to wiki:

In programming, operator overloading, sometimes termed operator ad hoc polymorphism, is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading is generally defined by a programming language, a programmer, or both.

In other words, you can add your own functionality to operators of your objects, i.e.:

cat1 + cat2

I wanted to play with this idea of making Animal objects and overloading the operators to do so fun things. So I had to make classes for my animals:


Now that I can make cat and dog objects, I thought that when you add two animals together it should do this:

animal1 + animal2
"animal2 is animal1's best friend"
[<Cat name: animal2 >]

When you have animal1 and then you bring in animal2, they’ll become best friends. But if animal1 is cranky or very unfriendly and you bring in animal2, animal1 may think that they are mortal enemies for coming around them.



The fun part was figuring out what happens when you multiply animals!

litter = dog1 * dog2
[<Dog name:'bob'>, <Dog name:'jill'>]

First I had to check if the two objects are the same species and if they are, then I generate a random number for the size of their littler. Then I loop over the range of the random number, creating a new instance of the parent’s class and returning all the instances in a list!


luna*palI’ve been working on this on the side for a day or two and I’ve had a blast. Check out a quick video from DevelopHerDevelopHim for a walk through the code below!

Check out my code on github and make your own cats, dogs, pandas, hamsters, rabbits, frogs, monkeys, mice and fish!

While I was working on this, I shared it with  Sarah, a coworker. She found a really fun module that displays emoji that she thought that I would like. Thank so much much for sharing this with me!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s