如何在自己的模块中导入/调用文件



我试图通过创建一个简单的模块来了解如何编写自己的模块,但我似乎不了解如何使用__init__文件,整个导入工作都很好。

现在我有一个名为"helloWorld"的包,其结构如下:

helloWorld
__init__.py
helloWorldFile.py
helloBonjourFile.py

这些是每个文件的内容:

__init__.py:

from helloWorldFile import helloWorldClass

helloWorldFile.py:

import helloBonjourFile
class helloWorldClass():
def __init__(self):
self.keyword = 'Hello Beautiful World'
def hello(self):
print self.keyword
helloBonjourFile.run()

helloBunjourFile.py:

def run():
print 'Bonjour Mon Ami!'

因此,我的想法是,我想从"helloWorldFile"运行"helloBonjourFile"中的任何内容,所以我尝试在Python shell中运行它:

import helloWorld
reload(helloWorld)
helloWorld.helloWorldClass().hello()

它打印出"你好,美丽的世界"部分很好,但在那之后,我一直收到一个错误:

属性错误:"module"对象没有属性"run"

我很确定我做得不对,我如何正确运行"helloWorld"one_answers"helloBonjour"的内容?我想尽量减少实际运行这些东西的文件。。。

如果可能的话,我也想找出一种方法,将论点传递到"你好"中。。。

我发现,对于其他可能有类似问题的人来说,这是由编辑一个文件并尝试在同一环境中从自定义模块运行引起的,并通过对每个文件运行reload()命令来解决。但是你必须按照导入文件的顺序来做,在我的情况下,我必须按照以下顺序重新加载:

reload(helloBounjourFile)
reload(helloWorldFile)
reload(helloWorld)

这应该会奏效。。。。如果它不多尝试几次以刷新(至少对我有效)。。。

最新更新