How to dynamically create a class instance in Python, python instance

Source: Internet
Author: User

How to dynamically create a class instance in Python, python instance

Introduction

In Java, we can use reflection to create class instances based on class names. How can we implement similar functions in Python?

In fact, there is a builtin Function import in Python. We can use this function to dynamically load some modules at runtime. 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, create a directory named my_modules, which contains three files.

* Init. py: module File
* My_module.py: Test Module
* My_another_module: Another Test Module

My_module.py

from my_modules.my_another_module import *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 packaged with pyinstaller, if the preceding code is used, the following error occurs when running the packaged program.

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

The error occurs because pyinstaller did not analyze the modules under my_modules when packaging the analysis class. Therefore, an error is reported during running.

Solution 1:

Manually import the module under my_modules in test. py. For details, see the first line in the following code. 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 2:

When using pyinstaller for packaging, specify "-hidden-import" as follows:

pyinstaller -D --hidden-import my_modules.my_module test.py

Solution 3:

Dynamically modify the path of python runtime. See the first two lines in the following code. path can be passed in through environment variables or parameters. Obviously, this method is 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()

The above section describes how to dynamically create a class instance in Python. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.