python - 使用同一类的方法为类导入模块
问题描述
我正在设计一个 python 类,我将在其中编写一个方法,例如import_modules()
,我将向该方法传递要在此类中导入的模块列表。是否可以import
在运行时为同一类使用这些模块?
class Base():
def import_modules(self,modules):
#import all the passed modules into this class
def use_module(self):
imported_module.some_function()
解决方案
您可以使用 __import__ 在运行时导入模块,并使用 __setattr__ (name, object) 设置对象的属性
class Base():
def import_modules(self,modules):
for m in modules:
self.__setattr__(m, __import__(m))
def use_module(self):
print(self.sys.platform)
b = Base()
b.import_modules(['sys'])
b.use_module()
推荐阅读
- jq - 如何将函数应用于jq中的多个字段
- reactjs - 按 Escape 关闭 Material UI 工具提示
- python - 将 DataFrame 作为新列附加
- javascript - Reactjs 如何从 Azure 存储容器下载文件
- excel - 基于矩阵隐藏/取消隐藏Excel工作表
- node.js - 我正在尝试为 node.js 创建一个登录页面,但在访问数据库中保存的数据时遇到问题
- php - Laravel websocket 与 vue.js 实时聊天
- java - Jenkins 权限被拒绝 /usr/share/maven 无法构建测试
- python - Mac用brew安装python3.6
- java - 如何模拟系统环境