简体   繁体   中英

Importing a module for all methods of an instance in Python3

I encountered a problem whilst importing a module in a Python3 class:

I am importing a module in the __init__ method of my class. 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. 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. I attempt to declare the import at class level, but the code doesn't work.

I python the function are first-citizen so we can save function in a variable. You should save the function you need in variables when you are in __init__() :

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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