__add__ to support addition of different types?

2024/10/5 20:14:04

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?

Answer

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 additionelse: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.

https://en.xdnf.cn/q/73220.html

Related Q&A

How to open .ndjson file in Python?

I have .ndjson file that has 20GB that I want to open with Python. File is to big so I found a way to split it into 50 peaces with one online tool. This is the tool: https://pinetools.com/split-files N…

loading a dataset in python (numpy) when there are variable spaces delimiting columns

I have a big dataset contains numeric data and in some of its rows there are variable spaces delimiting columns, like:4 5 6 7 8 9 2 3 4When I use this line:dataset=numpy.loadtxt("dataset.txt&q…

how to organise files with python27 app engine webapp2 framework

Ive gone through the getting started tut for python27 and app engine: https://developers.google.com/appengine/docs/python/gettingstartedpython27/By the end of the tut, all the the classes are in the sa…

Keras MSE definition

I stumbled across the definition of mse in Keras and I cant seem to find an explanation.def mean_squared_error(y_true, y_pred):return K.mean(K.square(y_pred - y_true), axis=-1)I was expecting the mean …

How do I adjust the size and aspect ratio of matplotlib radio buttons?

Ive been trying for hours to get the size and aspect ratio of a simple list of radio buttons correct with no success. Initially, import the modules:import matplotlib.pyplot as plt from matplotlib.widge…

App engine NDB: how to access verbose_name of a property

suppose I have this code:class A(ndb.Model):prop = ndb.StringProperty(verbose_name="Something")m = A() m.prop = "a string value"Now of course if I print m.prop, it will output "…

How do I load specific rows from a .txt file in Python?

Say I have a .txt file with many rows and columns of data and a list containing integer values. How would I load the row numbers in the text file which match the integers in the list?To illustrate, sa…

How to check in python if Im in certain range of times of the day?

I want to check in python if the current time is between two endpoints (say, 8:30 a.m. and 3:00 p.m.), irrespective of the actual date. As in, I dont care what the full date is; just the hour. When I c…

Python __class__()

In Pythons documentation __class__ is described as an attribute. In the object type (the metaclass), __class__ appears to be a method.If we do:>>> class Foo:pass>>> a = Foo() >>…

how to handle ever-changing password in sqlalchemy+psycopg2?

I inherited some code that uses sqlalchemy with psycopg2, which needs to run on AWS. RDS Postgres supports iam-based authentication, but the way it does it is rather kludgy: you request a temporary pas…