Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__add__ to support addition of different types?

Tags:

Would be very easy to solve had python been a static programming language that supported overloading. I am making a class called Complex which is a representation of complex numbers (I know python has its own, but i want to make one myself), where a is the real number and b is the imaginary (Complex(a, b)). It should support adding Complex instances together (Complex(2, 4) + Complex(4, 5) = Complex(6, 9)), as well as adding an integer (Complex(2, 3) + 4 = Complex(6, 3)). However, due to the nature of python...

__add__(self, other):

...I have to choose which the class will support, because it won't recognize types at compile-time, as well as not supporting overloading of functions. What is the best solution? Do I have to write an if statement in relation to the datatype of the other parameter?

like image 612
Snusifer Avatar asked Sep 06 '19 23:09

Snusifer


People also ask

What is the __ add __ method in Python?

The __add__() method in Python is a special method that defines what happens when you add two objects with the + operator.

What is __ str __ in Python?

Python __str__()This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.

What is __ new __ in Python?

In the base class object , the __new__ method is defined as a static method which requires to pass a parameter cls . cls represents the class that is needed to be instantiated, and the compiler automatically provides this parameter at the time of instantiation.

What is __ repr __?

According to the official documentation, __repr__ is used to compute the “official” string representation of an object and is typically used for debugging.


1 Answers

What you could do is check for the thing being of instance Complex, and if not, turn it into one, like so:

def __add__(self, other):
    if isinstance(other, Complex):
        # do addition
    else:
        return self + Complex(other, 0)

That of course does not eliminate type checking, but it reuses whatever you are doing in __init__ (which is probably checking if input is int or float).

If at the moment you do not do type checking in init, it is probably a good idea, and this looks reasonable, excepting built-in complex type.

like image 140
Andrei Avatar answered Oct 13 '22 03:10

Andrei