Dynamically create class instance code

  • 2020-04-02 09:31:26
  • OfStack

Such as:
The import mymodule
Myobject = mymodule. Myclass ()
or
The from mymodule import myclass
Myobject = myclass ()

If you want to create an instance of a class dynamically in your program, do the same thing in two steps, for example:
M = __import__ (" mymodule ")
C = getattr (m, 'myclass)
Myobject = c ()

Note, however, that if myclass is not in the auto-export list of mymodule (s), then it must be imported explicitly, for example:
M = __import__ (' mymodule, globals (), locals (), [' myclass '])
C = getattr (m, 'myclass)
Myobject = c ()

To encapsulate some of the specifications, you can do this:
Code
 
class Activator: 
''' This class is used to dynamically create instances of classes ''' 
@staticmethod 
def createInstance(class_name, *args, **kwargs): 
''' Dynamically create an instance of the class.  
[Parameter] 
class_name -  The full name of the class (including the module name)  
*args -  The parameters required by the class constructor (list) 
*kwargs -  The parameters required by the class constructor (dict) 
[Return] 
 An instance of a class created dynamically  
[Example] 
class_name = 'knightmade.logging.Logger' 
logger = Activator.createInstance(class_name, 'logname') 
''' 
(module_name, class_name) = class_name.rsplit('.', 1) 
module_meta = __import__(module_name, globals(), locals(), [class_name]) 
class_meta = getattr(module_meta, class_name) 
object = class_meta(*args, **kwargs) 
return object 

Related articles: