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?
The __add__() method in Python is a special method that defines what happens when you add two objects with the + operator.
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.
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.
According to the official documentation, __repr__ is used to compute the “official” string representation of an object and is typically used for debugging.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With