首页 > 解决方案 > 使用同一类的方法为类导入模块

问题描述

我正在设计一个 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()

标签: pythonclassimport

解决方案


您可以使用 __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()



推荐阅读