python动态import

来源:互联网 发布:c2运输机知乎 编辑:程序博客网 时间:2024/06/06 02:00

一个例子

目录结构如下:

.├── student.py└── test.py

student.py:

class Student(object):    def say(self):        return 'student'

test.py:

module_name = __import__('student', fromlist=['Student'])class_name = getattr(module_name, 'Student')print class_name().say()

注意

  • __import__('A.B.C', fromlist=[])时,即fromlist为空时,函数返回的是module A;当fromlist不为空时,函数返回的是module C


Ref

Why does Python’s __import__ require fromlist?

原创粉丝点击