Python operator overloading, allows you to define the behavior of operators (+, -, *, /, etc.) for objects of custom classes. By implementing special methods or dunder methods (double underscore methods), you can customize how operators work with your objects.
Here are a few examples of operator overloading in Python:
- Addition Operator (+):
class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): if isinstance(other, Point): return Point(self.x + other.x, self.y + other.y) elif isinstance(other, (int, float)): return Point(self.x + other, self.y + other) else: raise TypeError("Unsupported operand type.") # Create two Point objects p1 = Point(1, 2) p2 = Point(3, 4) # Add two Point objects p3 = p1 + p2 print(p3.x, p3.y) # Output: 4, 6 # Add a Point object with an integer p4 = p1 + 5 print(p4.x, p4.y) # Output: 6, 7
In the example above, the Point
class defines the __add__
method, which is called when the +
operator is used with Point
objects. It allows adding two Point
objects together by combining their x
and y
coordinates. It also supports adding an integer or float to a Point
object by adding the value to both the x
and y
coordinates.
- String Representation (str):
class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"Person(name={self.name}, age={self.age})" # Create a Person object person = Person("Alice", 25) # Display the object as a string print(person) # Output: Person(name=Alice, age=25)
In the example above, the Person
class defines the __str__
method, which is called when the str()
function is used or when the object is converted to a string implicitly. It returns a formatted string representation of the Person
object.
- Comparison Operators (==, !=, >, <, >=, <=):
class Rectangle: def __init__(self, length, width): self.length = length self.width = width def __eq__(self, other): if isinstance(other, Rectangle): return self.length == other.length and self.width == other.width else: return False # Create two Rectangle objects rect1 = Rectangle(5, 10) rect2 = Rectangle(5, 10) rect3 = Rectangle(3, 6) # Compare two Rectangle objects print(rect1 == rect2) # Output: True print(rect1 == rect3) # Output: False
In the example above, the Rectangle
class defines the __eq__
method, which is called when the ==
an operator is used with Rectangle
objects. It compares the length
and width
attributes of two rectangles and returns True
if they are equal.