To create an instance of a class in Python, you must first import the class or the module to which the class belongs. For example:
Import mymodule
Myobject = mymodule. myclass ()
Or
From mymodule import myclass
Myobject = myclass ()
If you want to dynamically create a class instance in the program, you also need to take two steps, for example:
M = _ import _ ('mymodule ')
C = getattr (m, 'myclass ')
Myobject = c ()
Note: If myclass is not in the automatic export column table (_ all _) of mymodule, it must be explicitly imported. for example:
M = _ import _ ('mymodule', globals (), locals (), ['myclass'])
C = getattr (m, 'myclass ')
Myobject = c ()
To encapsulate some specifications, you can do this:
Code
The code is as follows:
Class Activator:
''' This class is used to dynamically create an instance of the class '''
@ Staticmethod
Def createInstance (class_name, * args, ** kwargs ):
''' Dynamically creates a class instance.
[Parameter]
Class_name-full name of the class (including the module name)
* Args-list of parameters required by the class constructor)
* Kwargs-parameters required by the class constructor (dict)
[Return]
Dynamically created class instances
[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