Dynamically creating class instance code

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 have to take two steps, for example:
m = __import__ (' MyModule ')
c = GetAttr (M, ' MyClass ')
MyObject = C ()

Note, however: if MyClass is not in the MyModule auto-export list (__all__), 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

The code is as follows:


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