【问题标题】:How to import/call between files in your own module?如何在您自己的模块中的文件之间导入/调用?
【发布时间】:2018-04-06 00:29:39
【问题描述】:

我试图通过尝试创建一个简单的模块来了解如何编写自己的模块,但我似乎不了解如何使用 __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()

helloBounjourFile.py:

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

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

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

它可以很好地打印出“Hello Beautiful World”部分,但之后我不断收到错误:

AttributeError: 'module' 对象没有属性 'run'

我很确定我做错了,我如何正确运行“helloWorld”和“helloBonjour”的内容?我想将实际运行这些东西的文件保持在最低限度......

如果可能的话,我还想找出一种将参数传递给“helloBonjour”的方法......

【问题讨论】:

    标签: python python-2.7 python-2.6


    【解决方案1】:

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

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

    这应该可以解决问题....如果它不尝试多次刷新(至少对我有用)...

    【讨论】:

      猜你喜欢
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 2021-05-18
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多