Fundamentals 7 min read

Master Python Operator Overloading: From Basics to Custom + and Comparison Operators

This article explains Python operator overloading, introduces special methods like __init__, __str__, __add__, and __lt__, provides step‑by‑step code examples for overloading the + operator and comparison operators, and demonstrates the results with clear output images.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python Operator Overloading: From Basics to Custom + and Comparison Operators

What Is Operator Overloading in Python?

Python allows operators to have different behavior depending on the operand types. This feature, called operator overloading, lets the same operator perform arithmetic, concatenation, or custom actions based on context.

Special Methods (Dunder Methods)

Methods whose names start and end with double underscores (e.g., __init__, __str__) are special methods. They are invoked automatically by Python in certain situations, such as object creation or when converting an object to a string.

Example: A Simple Point Class

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

Attempting to add two Point objects without overloading results in a TypeError because Python does not know how to handle + for custom objects.

Defining __str__ for Readable Output

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __str__(self):
        return "({0},{1})".format(self.x, self.y)

Now print(Point(3,7)) displays (3,7) instead of the default object representation.

Overloading the + Operator

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __str__(self):
        return "({0},{1})".format(self.x, self.y)
    def __add__(self, other):
        x = self.x + other.x
        y = self.y + other.y
        return Point(x, y)

Testing:

p1 = Point(2,3)
p2 = Point(-1,2)
print(p1 + p2)

The expression p1 + p2 now calls p1.__add__(p2) and returns a new Point with coordinates (1,5).

Overloading Comparison Operators

Python also allows overloading of comparison operators by defining methods such as __lt__, __le__, __eq__, __ne__, __gt__, and __ge__. For example, to compare points by their distance from the origin:

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
    def __str__(self):
        return "({0},{1})".format(self.x, self.y)
    def __lt__(self, other):
        self_mag = (self.x ** 2) + (self.y ** 2)
        other_mag = (other.x ** 2) + (other.y ** 2)
        return self_mag < other_mag

Running the following tests demonstrates the overloaded < operator:

print(Point(1,1) < Point(-2,-3))
print(Point(1,1) < Point(0.5,-0.2))
print(Point(1,1) < Point(1,1))

Summary

The article introduces Python operator overloading, explains special methods, and provides concrete examples for overloading the + operator and comparison operators. Through code snippets and output images, readers can see how to customize operator behavior for their own classes.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonCode ExamplesTutorialoperator overloadingSpecial Methods
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.