Dynamically creating class instances in Python

Source: Internet
Author: User

Introduction to dynamically creating class instances in Python

In Java we can use reflection to create class instances based on the class name, so how do we implement similar functionality in Python?

In fact, in Python there is a builtin function import, we can use this function to dynamically load some modules at run time. As follows:

def createInstance(module_name, class_name, *args, **kwargs):    module_meta = __import__(module_name, globals(), locals(), [class_name])    class_meta = getattr(module_meta, class_name)    obj = class_meta(*args, **kwargs)    return obj
Example

First we build a directory my_modules, which includes three files
* init. PY: module file
* my_module.py: Test module
* My_another_module: Another module for testing

my_module.py
 fromMy_modules.my_another_moduleImport* class MyObject(object):     def test(self):        Print ' Myobject.test 'MyObject1 (). Test () MyObject2 (). Test () Myanotherobject (). Test () class MyObject1(object):     def test(self):        Print ' Myobject1.test ' class MyObject2(object):     def test(self):        Print ' Myobject2.test '
my_another_module.py
class MyAnotherObject(object):    def test(self):        print‘MyAnotherObject.test‘
test.py
def createInstance(module_name, class_name, *args, **kwargs):    module_meta = __import__(module_name, globals(), locals(), [class_name])    class_meta = getattr(module_meta, class_name)    obj = class_meta(*args, **kwargs)    return objobj = createInstance("my_modules.my_module""MyObject")obj.test()
MyObject.testMyObject1.testMyObject2.testMyAnotherObject.test
Pyinstaller Integration

For applications that use Pyinstaller packaging, if you use the code above, running the packaged program will cause the following error

Traceback (most recent call last):  "test.py"12in <module>    obj = createInstance("my_modules.my_module""MyObject")  "test.py"7in createInstance    module_meta = __import__(module_name, globals(), locals(), [class_name])ImportError: No module named my_modules.my_moduleFailed to execute script test

The reason for the error here is that pyinstaller in the packaging analysis class is not analyzed to my_modules the following module, so run an error.

Solution One:

To manually import the module under My_modules in test.py, see the first line in the code below. This method is the simplest, but obviously not very good.

import my_modules.my_moduledef createInstance(module_name, class_name, *args, **kwargs):    module_meta = __import__(module_name, globals(), locals(), [class_name])    class_meta = getattr(module_meta, class_name)    obj = class_meta(*args, **kwargs)    return objobj = createInstance("my_modules.my_module""MyObject")obj.test()
Solution Two:

When packaging with Pyinstaller, specify "–hidden-import", as follows

pyinstaller -D --hidden-import my_modules.my_module test.py
Solution Three:

To dynamically modify the Python runtime path, see the first two lines in the code below, where path can be passed in by environment variables or parameters. Obviously this method is much more flexible than the first two methods.

import syssys.path.append(...)def createInstance(module_name, class_name, *args, **kwargs):    module_meta = __import__(module_name, globals(), locals(), [class_name])    class_meta = getattr(module_meta, class_name)    obj = class_meta(*args, **kwargs)    return objobj = createInstance("my_modules.my_module""MyObject")obj.test()

Please indicate the link of this article in the form of a link
This article link: http://blog.csdn.net/kongxx/article/details/65626418

Dynamically creating class instances in Python

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.