1

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.

1
  • 3
    type(self)(new_param) Commented Feb 5, 2018 at 16:28

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.