Search code examples
pythoninheritanceinstantiation

Instantiate an child object directly from a parent object


I have two objects one inherits from the other and the only difference between them is a few attribute fields:

class Parent:
    def __init__(self,a, b):
        self.a = a
        self.b = b

    def methodA(self):
        # do something
        pass

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

I have an instance of the parent object and I want to find a fast way in python to create an instance of the child object which only has one additional field by using the already existing parent object.

Is there a python way or module that lets you do that easily. IN my real code the parent class has hundreds of fields and it is a bit inefficient to just reassign its value.


Solution

  • Ok the other suggestions for making a method that takes in parent attributes and creates a child object is ok but adds unnecessary code I think. I made this solution, which I ended up using. It doesnt accept the parent object directly in as an argument but it is more concise I think:

    class Parent:
        def __init__(self, a, b):
            self.a = a
            self.b = b
            
    class Child(Parent):
        def __init__(self,c, **kwargs):
            self.c = c
            super().__init__(**kwargs)
    
    # So if I start with this parent object
    parent_args = {"a":23,"b":"iuhsdg"}
    parent =Parent(**parent_args)
    
    # I then make child with all the parent attributes plus some more
    child_args = {"c":567}
    child_args.update(vars(parent))
    child = Child(**child_args)