【问题标题】:Importing a module for all methods of an instance in Python3在 Python3 中为实例的所有方法导入模块
【发布时间】:2020-09-01 10:24:23
【问题描述】:

在 Python3 类中导入模块时遇到问题:

我正在我班级的__init__ 方法中导入一个模块。它在这种方法中工作正常,但是有没有办法在另一种方法中再次使用这个模块?我尝试将模块保存到 self. 变量中,仍然无法正常工作。

当然我可以在方法中再次导入它,但我宁愿为我的所有方法导入模块,因为大多数方法都需要它。

下面我给你一些示例代码:

class Example(object)

   def __init__(self):

      import moduleName as module

      module.function() # works perfectly

      # Trying to save module for the whole instance:
      self.module = module

   def method(self):

      module.function() # Does not recognize module
      self.module.function() # Does not recognize attribute either

如果有人可以帮助我,我会很高兴:)

【问题讨论】:

    标签: python python-3.x methods import module


    【解决方案1】:

    我不知道在 python 中我们是否可以将模块保存在变量中。我尝试在类级别声明导入,但代码不起作用。

    我的python函数是第一公民,所以我们可以将函数保存在一个变量中。当你在__init__()时,你应该把你需要的函数保存在变量中:

    import module as mod 
    mod.function()
    self.function = mod.function
    

    过了一会儿……

    您可以动态加载模块,但为此您必须导入模块importlib。这是代码:

    import importlib
    
    class MyClass:
        def __init__(self):
            self.module = importlib.import_module("module") 
            self.module.function()
    
        def func(self):
            self.module.function()
    
    c = MyClass()
    c.func()
    

    还有 imp 模块。

    【讨论】:

      猜你喜欢
      • 2020-07-15
      • 1970-01-01
      • 2016-03-20
      • 1970-01-01
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多