python动态import

一个例子

目录结构如下:

.
├── 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?

你可能感兴趣的:(python,python)