Python's dynamic import module and class

Source: Internet
Author: User

Dynamic Import Module

For example, I want to introduce a file at the end of all ". Py" files in a folder, but I don't need to introduce _init_.py.

First, we get a related array of strings through the Python string processing process.

The source code is as follows:

Import OS

N=[]
Dir1=os.listdir (' E:\ \webtest\test_case ')
for a in Dir1:
M=a.find ("Start")
if m!=-1:
Test=a.split ('. ') [1]
if test==' py ':
Test1=a.split ('. ') [0]
N.append (test1)

At this point the N output is a string-form list:

n=[' start_01 ', ' start_02 ', ' start_03 ', ' start_04 ']

At this point, if you want to import dynamically, use the _import_ () method, and refer to the official guidance document for the use of this method.

The source code is as follows:

Range (0,M):
A="Test_case" +"." +n[i]
Load=__import__ (a)

By looping we import the module that we want to test in turn.

Dynamic Import Class

We test_case the folder underground, we need to dynamically get start_01 to the Start_04 folder under the corresponding class, this piece for easy invocation, our file name and class name are consistent.

The idea is as follows: First we get the premise of the class, is to obtain the module, just a dynamic import module, and did not get import module.

Get the following source code:

Test2=[]
Range (0,M):
A="Test_case" +"." +n[i]
Load=__import__ (a)
A=getattr (Load,n[i]) #获取module
B=getattr (A,n[i]) #获取class
Test2.append (b)

This section of the source code completes the process of dynamically acquiring classes.

For the use of the GetAttr method, refer to the official website documentation for details.

Python's dynamic import module and class

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.