
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Overloading Operators in Python
Suppose you have created a Vector class to represent two-dimensional vectors, what happens when you use the plus operator to add them? Most likely Python will yell at you.
You could, however, define the __add__ method in your class to perform vector addition and then the plus operator would behave as per expectation −
Example
#!/usr/bin/python class Vector: def __init__(self, a, b): self.a = a self.b = b def __str__(self): return 'Vector (%d, %d)' % (self.a, self.b) def __add__(self,other): return Vector(self.a + other.a, self.b + other.b) v1 = Vector(2,10) v2 = Vector(5,-2) print v1 + v2
Output
When the above code is executed, it produces the following result −
Vector(7,8)
- Related Articles
- How does Overloading Operators work in Python?
- Overloading unary operators + in C++
- Overloading stream insertion () operators in C++
- Base Overloading Methods in Python
- Division Operators in Python?
- Basic Operators in Python
- What are base overloading methods in Python?
- Chaining comparison operators in Python
- String Special Operators in Python
- Python Arithmetic Operators
- Python Comparison Operators
- Python Assignment Operators
- Python Bitwise Operators
- Python Logical Operators
- Python Membership Operators

Advertisements