


Detailed explanation of using code to dynamically create class instances in Python
In Java we can create class instances based on class names through reflection, so how do we achieve 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
Introduction
In Java We can create class instances based on class names through reflection, so how do we achieve 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 we create a directory my_modules, which includes three files
* init.py: module file
* my_module.py: module for testing
* my_another_module: another module for testing
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 obj obj = createInstance("my_modules.my_module", "MyObject") obj.test() MyObject.test MyObject1.test MyObject2.test MyAnotherObject.test
pyinstaller integration
For applications packaged with pyinstaller, if you use the above code, the following error will occur when running the packaged programTraceback (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_module Failed to execute script test
Solution 1:
Manually import the module under my_modules in test.py, see the first line of the code below. This method is the simplest, but obviously not very good.import my_modules.my_module 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 obj = createInstance("my_modules.my_module", "MyObject") obj.test()
Solution 2:
When using pyinstaller to package, specify "--hidden- import", as followspyinstaller -D --hidden-import my_modules.my_module test.py
Solution three:
Dynamicly modify the python runtime path, see In the first two lines of the code below, we can pass path in through environment variables or parameters. Obviously this method is much more flexible than the first two methods.import sys sys.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 obj obj = createInstance("my_modules.my_module", "MyObject") obj.test()
The above is the detailed content of Detailed explanation of using code to dynamically create class instances in Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...
