How we can instantiate different python classes dynamically?

PythonServer Side ProgrammingProgramming

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
raja
Published on 25-Jan-2018 16:16:35
Advertisements