0
0
PythonHow-ToBeginner · 3 min read

How to Implement __add__ Method in Python for Custom Addition

In Python, implement the __add__ method inside your class to define how the + operator works for its objects. This method takes two parameters: self and other, and returns the result of adding them together.
📐

Syntax

The __add__ method is defined inside a class to customize the behavior of the + operator. It must accept two parameters: self (the current object) and other (the object to add). It returns the result of the addition.

python
class ClassName:
    def __add__(self, other):
        # code to add self and other
        return result
💻

Example

This example shows a simple Point class where __add__ adds the x and y coordinates of two points and returns a new Point object.

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

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

    def __repr__(self):
        return f"Point({self.x}, {self.y})"

p1 = Point(2, 3)
p2 = Point(4, 5)
p3 = p1 + p2
print(p3)
Output
Point(6, 8)
⚠️

Common Pitfalls

Common mistakes include not checking the type of other, which can cause errors if you try to add incompatible objects. Also, forgetting to return a new object or the correct result can lead to unexpected behavior.

Always ensure __add__ returns a new instance or a proper value representing the sum.

python
class Number:
    def __init__(self, value):
        self.value = value

    # Wrong: does not check type and returns None
    def __add__(self, other):
        self.value += other.value

    # Right: checks type and returns new instance
    def __add__(self, other):
        if not isinstance(other, Number):
            return NotImplemented
        return Number(self.value + other.value)
📊

Quick Reference

ConceptDescription
__add__(self, other)Defines behavior for + operator between objects
Return valueShould return the sum as a new object or value
Type checkingUse isinstance to handle unsupported types gracefully
NotImplementedReturn this if addition with other type is not supported

Key Takeaways

Implement __add__ to customize + operator for your class objects.
Always return a new object or correct sum value from __add__.
Check the type of the other object to avoid errors.
Return NotImplemented if the other object type is unsupported.
Use __repr__ or __str__ to make output readable when printing results.