create child class from parent class, same arguments

I have a parent class Parent and a child class Child that forwards all initialization arguments to Parent. (It only add a few methods.)

class Parent:
    def __init__(self, alpha, beta, zeta, omicron):
        self.alpha = alpha
        self.c = alpha + beta + zeta + omicron

class Child(Parent):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def show(self):
        print(self.alpha, self.c)

p = Parent(23.7, 0.0, 1.0, -4.1)

# create Child from p?
# c = ... ?

Given a parent class instance, how can I best create a child class instance from it?
I though could add something like

def from_parent(cls, parent):
    return cls(
        # parent.beta,
        # parent.zeta,
        # parent.omicron

but Parent doesn’t have all arguments that are necessary to create another instance from it.

Any hints?

>Solution :

There is no general way to do what you want. Any implementation will be specific to your classes.

However, in the case where the Child class doesn’t do anything at all in its __init__ (which is equivalent to not having an __init__ at all), you can actually change the class of the Parent object you already have:

parent.__class__ = Child

Note that this is modifying the object in place, it’s not making a new copy of the object that’s a Child.

Leave a Reply