Dynamically create class instance code _python

Source: Internet
Author: User
For example:
Import MyModule
MyObject = Mymodule.myclass ()
Or
From MyModule import MyClass
MyObject = MyClass ()

If you want to create a class instance dynamically in your program, you need to take two steps, for example:
m = __import__ (' MyModule ')
c = GetAttr (M, ' MyClass ')
MyObject = C ()

Note, however: if MyClass is not in the MyModule automatic Export list (__all__), you must explicitly import it, 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
Copy Code code as follows:

Class Activator:
' This class is used to dynamically create instances of the class '
@staticmethod
Def CreateInstance (Class_name, *args, **kwargs):
"Creates an instance of the class dynamically.
[Parameter]
Class_name-Full name of class (including module name)
*args-The parameters required by the Class Builder (list)
*kwargs-The parameters required by the Class Builder (DICT)
[Return]
Instance of a dynamically created class
[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.