Reputation: 810
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.
Upvotes: 1
Views: 2201
Reputation: 7206
You could use the fact that every instance has a pointer to its class under __class__
:
class Parent(object):
def __init__(self,param):
self.param = param
def copy(self):
new_param = some_complicated_stuff(self.param)
return self.__class__(new_param)
This will be Parent
for the above class, but Child
in the derived class.
Instead of self.__class__
, you can also use type(self)
, as @Eli Korvigo has said in the comments, or as said here.
Upvotes: 2