Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How can we do Python operator overloading with multiple operands?
You can do Python operator overloading with multiple operands just like you would do it for binary operators. For example, if you want to overload the + operator for a class, you'd do the following −
Example
class Complex(object):
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __add__(self, other):
real = self.real + other.real
imag = self.imag + other.imag
return Complex(real, imag)
def display(self):
print(str(self.real) + " + " + str(self.imag) + "i")
a = Complex(10, 5)
b = Complex(5, 10)
c = Complex(2, 2)
d = a + b + c
d.display()
Output
This will give the output −
17 + 17i
Advertisements
