简体   繁体   中英

Python inheritance: create child object in parent class

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM