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: 16-Jun-2020

744 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements