【发布时间】: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