Syntax error How we can instantiate different python classes dynamically?

How we can instantiate different python classes dynamically?



To instantiate the python class, we need to get the class name first. This is achieved by following code

def get_class( kls ):
    parts = kls.split('.')
    module = ".".join(parts[:-1])
    m = __import__( module )
    for comp in parts[1:]:
        m = getattr(m, comp)                
    return m

m is the class

We can instantiate this class as follows

a = m()
b = m(arg1, arg2) # passing args to the constructor
Updated on: 2020-06-16T08:29:21+05:30

892 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements