879277. Operator Overloading In Python
Easy
Operator Overloading In Python
Slug: operator-overloading-in-python
Difficulty: Easy
Id: 879277
Topic Tags: None
Company Tags: None
Summary
Operator overloading in Python is a technique that allows developers to redefine the behavior of operators such as +, -, *, /, <, >, etc. for user-defined classes. This feature enables objects of custom classes to support standard mathematical and logical operations, making it easier to work with complex data structures.
Detailed Explanation
The goal is to create a class that supports basic arithmetic operations like addition, subtraction, multiplication, and division. We will define a ComplexNumber class with real and imaginary parts, and then overload the corresponding operators to perform these operations correctly.
Here's the step-by-step breakdown of the solution:
- Define the
ComplexNumberclass:
class ComplexNumber {
double real, imag;
public ComplexNumber(double real, double imag) {
this.real = real;
this.imag = imag;
}
@Override
public String toString() {
return String.format("%f + %fi", real, imag);
}
public ComplexNumber add(ComplexNumber other) {
if (other instanceof ComplexNumber)
return new ComplexNumber(real + ((ComplexNumber) other).real, imag + ((ComplexNumber) other).imag);
else throw new TypeError("Unsupported operand type for +");
}
public ComplexNumber subtract(ComplexNumber other) {
if (other instanceof ComplexNumber)
return new ComplexNumber(real - ((ComplexNumber) other).real, imag - ((ComplexNumber) other).imag);
else throw new TypeError("Unsupported operand type for -");
}
public ComplexNumber multiply(ComplexNumber other) {
if (other instanceof ComplexNumber)
return new ComplexNumber(
real * ((ComplexNumber) other).real - imag * ((ComplexNumber) other).imag,
real * ((ComplexNumber) other).imag + imag * ((ComplexNumber) other).real
);
else throw new TypeError("Unsupported operand type for *");
}
public ComplexNumber divide(ComplexNumber other) {
if (other instanceof ComplexNumber && ((ComplexNumber) other).real ** 2 + ((ComplexNumber) other).imag ** 2 != 0)
return new ComplexNumber(
(real * ((ComplexNumber) other).real + imag * ((ComplexNumber) other).imag) / (((ComplexNumber) other).real ** 2 + ((ComplexNumber) other).imag ** 2),
(imag * ((ComplexNumber) other).real - real * ((ComplexNumber) other).imag) / (((ComplexNumber) other).real ** 2 + ((ComplexNumber) other).imag ** 2)
);
else throw new ZeroDivisionError("Cannot divide by zero");
}
}