【问题标题】:Import modules for a class using method of the same class使用同一类的方法为类导入模块
【发布时间】:2019-12-19 17:19:36
【问题描述】:

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

【问题讨论】:

    标签: python class import


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-13
      • 2021-10-06
      • 1970-01-01
      • 2020-12-25
      • 1970-01-01
      • 2020-11-15
      • 2017-11-04
      • 1970-01-01
      相关资源
      最近更新 更多