Code for dynamically creating a class instance-Python tutorial

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.