动态导入模块

1.创建一个简单的hello文件,里面只有一个类A,A属性为name

 

2.获取文件下面的未知类有哪些?

当只知道需要导入的类名称,但是不知道具体位置,如何动态导入?

import importlib.util
import inspect

# 文件夹下面有个脚本,下面只有一个类:
from test_import import hello
# 给定文件,获取对应目录下面的全部类==============================================
members = inspect.getmembers(hello)
classes = [member[1] for member in members if inspect.isclass(member[1])]
class_name_list = [cls.__name__ for cls in classes]
print(class_name_list)

# 假如知道类名称,但是不知道具体位置,动态导入演示==================================
module_name = class_name_list
module = importlib.import_module("test_import.hello")
class_obj = getattr(module, class_name_list[0])
# 调用类的属性,或者类方法======================================================
class_obj().name

 

 3.inspect:获取是那个文件调用了当前类

class A:
    def __init__(self):
        file_path = inspect.stack()[1][1]
        print(f"是{file_path}调用了当前类")
        # E:\代码项目练习\z_test.py

 

posted @ 2023-07-25 21:54  zwx901323  阅读(4)  评论(0编辑  收藏  举报