I have a parent class, with a method that returns a new object. I'd like that object to be of the same type as self (ie Parent if called within Parent class, Child if called in a Child instance).
class Parent(object):
def __init__(self,param):
self.param = param
def copy(self):
new_param = some_complicated_stuff(self.param)
return Parent(new_param)
class Child(Parent):
pass
C = Child(param)
D = C.copy()
Here D = C.copy()
will be of type Parent, regardless of the class C
. I would like to have copy return an instance of the same class as C
, while keeping the "some_complicated_stuff" part in the parent class in order to avoid code duplicate.
Context: Parent is an abstract group structure, "copy" returns subgroups (doing a series of algebraic operations), and I have many different Child classes that use this method.