Home > Mobile >  Instantiate an child object directly from a parent object
Instantiate an child object directly from a parent object

Time:05-16

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.

CodePudding user response:

The canonical solution is to add a class method to Child that works as a constructor. It takes a Parent instance and returns the Child instance with the proper attributes.

For example:

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)

    @classmethod
    def from_parent(cls, parent, c):
        return cls(a=parent.a, b=parent.b, c=c)


p = Parent(a=1, b=2)
c = Child.from_parent(parent=p, c=3)
print(c.a, c.b, c.c)  # output: 1 2 3

I would argue that your Parent class having hundreds of attributes is irrelevant to the answer. Yes, it's tedious having to explicitly write every attribute of the Parent instance in the from_parent method, but that's simply a limitation of having a class with that many attributes anyway. Possibly, a better design choice would be to encapsulate groups of Parent attributes into proper classes, so that only those instances need to be delivered to the Child class upon initialization.

CodePudding user response:

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)
  • Related