I wrote a parent class where I define a few functions (examples __mul__, __truediv__, etc.) that all of the child classes should have. These functions should keep the type of the child class after they have been executed.
Here some code to explain what I mean:
class Magnet():
def __init__(self, length, strength):
self.length = length
self.strength = strength
return
def __mul__(self, other):
if np.isscalar(other):
return Magnet(self.length, self.strength * other)
else:
return NotImplemented
class Quadrupole(Magnet):
def __init__(self, length, strength, name):
super().__init__(length, strength)
self.name = name
return
Now if I do this:
Quad1 = Quadrupole(2, 10, 'Q1')
Quad2 = Quad1 * 2
Then Quad1 is of type '__main__.Quadrupole' and Quad2 of type '__main__.Magnet'.
I would like to know how to do this such that the type of the child is kept and it is not recast into a parent type. One solution would be to redefine these functions in the child classes and change
if np.isscalar(other):
return Magnet(self.length, self.strength * other)
to
if np.isscalar(other):
return Quadrupole(self.length, self.strength * other)
but the main reason to do inheritance was to not copy paste code. Maybe something like super() but downwards or maybe some placeholder for the class type...
I'm thankful for any help.
Adopted solution
Using
return type(self)(self.length, self.strength * other)
does the charm. It raises an error because I forgot to add the 'name' argument in the Magnet.__init__() (my original code does, but messed up when simplifying for the example).
I also found the same question here: Returning object of same subclass in __add__ operator