[Tutor] Creating instance of child classes dynamically

Cameron Simpson cs at cskk.id.au
Sun Feb 7 17:39:39 EST 2021


On 07Feb2021 20:48, Sachit Murarka <connectsachit at gmail.com> wrote:
>I meant base class in a different python file. It was a typo.

That's ok. You just need to import that base class into the files 
defining the subclasses:

    from parent import Parent

    class Child1(Parent):
        def process(self):
            ...

>My use case is , Parent will define the template. On the run type user 
>will
>pass a string , eg String will be child1 or child2 etc. Accordingly we want
>to call process function of that class.
>
>Please note each child class is in a different file . In actual solution
>there will be many children and we can not put all children in a single py
>file.

That's also ok. But your code which makes instances of each child class 
needs to import them:

    parser.py:
    from child1 import Child1
    from child2 import Child2
    ...
    ... pick the right subclass for your input here ...

>As using reflections we can create objects at run time by giving fully
>qualified class names(Atleast in java).

That's not going to play so well in Python. But a little similar to 
Alan's approach (which maps names to process() implementations), you can 
map names to classes:

    from child1 import Child1
    from child2 import Child2

    class_map = {
        'child1name': Child1,
        'child2name': Child2,
    }

    def Child(name, *a, **kw):
        ''' Create an instance of a subclass based on `name`.
        '''
        cls = class_map[name]
        return cls(*a, **kw)

    ... parsing code ...
    name = ... get the right name from the input data ...
    child = Child(name, initialiser-args-here...)
    ...
    child.process()

and that calls your factory function "Child" with the name, and the 
factory picks the desired class and makes a new instance.

You can do more elaborate things, like keep a registry of classes in the 
Parent class, have each child subclass register itself, and consult that 
registry from the Child() factory above. But start simple.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list