简体   繁体   English

在 Python3 中为实例的所有方法导入模块

[英]Importing a module for all methods of an instance in Python3

I encountered a problem whilst importing a module in a Python3 class:在 Python3 class 中导入模块时遇到问题:

I am importing a module in the __init__ method of my class.我正在 class 的__init__方法中导入一个模块。 It works fine in this method, however is there a way to use this module again in another method?它在这种方法中工作正常,但是有没有办法在另一种方法中再次使用这个模块? I tried saving the module into a self.我尝试将模块保存到self. variable, still doesn't work.变量,仍然不起作用。

Of course I could import it again inside the method, but I would rather import the module for all of my methods, since most of them need it.当然我可以在方法中再次导入它,但我宁愿为我的所有方法导入模块,因为它们中的大多数都需要它。

I'll give you some example code below:我将在下面为您提供一些示例代码:

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

I'd be happy if someone could help me with this:)如果有人可以帮助我,我会很高兴:)

I don't know if in python we can save a module in a variable.我不知道在 python 中是否可以将模块保存在变量中。 I attempt to declare the import at class level, but the code doesn't work.我尝试在 class 级别声明导入,但代码不起作用。

I python the function are first-citizen so we can save function in a variable.我 python 和 function 是第一公民,所以我们可以将 function 保存在一个变量中。 You should save the function you need in variables when you are in __init__() :当您在__init__()中时,您应该将所需的 function 保存在变量中:

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

After a while...过了一会儿...

You can load a module dinamically, but to this you have to import the module importlib .您可以动态加载模块,但为此您必须导入模块importlib This is the code:这是代码:

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()

There is also the imp module.还有 imp 模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM