Home > Back-end >  create child class from parent class, same arguments
create child class from parent class, same arguments

Time:12-13

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

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

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

Any hints?

CodePudding user response:

In this case, it seems Parent.__init__ does too much. The additional three arguments are independent of an instance of Parent; they are just one way to define the c attribute.

class Parent:
    def __init__(self, c):
        self.alpha = alpha
        self.c = c

    @classmethod
    def from_parameters(cls, alpha, beta, zeta, omicron):
        return cls(alpha, alpha   beta   zeta   omicron)


class Child(Parent):

    # Seemingly belongs in Parent, not here.
    def show(self):
        print(self.alpha, self.c)

    @classmethod
    def from_parent(cls, p):
        return cls(p.alpha, p.c)


p = Parent.from_parameters(23.7, 0.0, 1.0, -4.1)
c = Child.from_parent(p)

CodePudding user response:

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.

  • Related