Python:从导入的文件调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19056240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:40:02  来源:igfitidea点击:

Python: calling function from imported file

pythonpython-2.7

提问by RageCage

How do you call a function from an imported file? for example:

如何从导入的文件中调用函数?例如:

Test:

测试:

import test2
def aFunction():
    print "hi there"

Test2:

测试2:

import test
aFunction()

This give me a name error, saying my function isn't defined. I've also tried:

这给了我一个名称错误,说我的函数没有定义。我也试过:

from test import aFunction

And:

和:

from test import *

I've also tried not importing test2 in test. I'm coming to Python from C++, so I fear I'm missing something blatantly obvious to veteran Python progammers...

我也试过不在测试中导入 test2。我是从 C++ 开始学习 Python 的,所以我担心我错过了一些对资深 Python 程序员来说显而易见的东西......

采纳答案by Martijn Pieters

You are creating a circular import. test.pyimports test2.pywhich tries to import test.py.

您正在创建循环导入。test.py进口test2.py这些尝试导入test.py

Don't do this. By the time test2imports test, that module has not completed executing all the code; the function is not yet defined:

不要这样做。到test2import 时test,该模块还没有完成所有代码的执行;该函数尚未定义:

  • testis compiled and executed, and an empty module object is added to sys.modules.

  • The line import test2is run.

    • test2is compiled and executed, and an empty module object is added to sys.modules.

    • The line import testis run.

      • testis already present as a module in sys.modules, this object is returned and bound to the name test.
    • A next line tries to run test.aFunction(). No such name exists in test. An exception is raised.

  • The lines defining def aFunction()are never executed, because an exception was raised.

  • test被编译和执行,并且一个空的模块对象被添加到sys.modules.

  • 线路import test2运行。

    • test2被编译和执行,并且一个空的模块对象被添加到sys.modules.

    • 线路import test运行。

      • test已作为模块存在sys.modules,则返回此对象并绑定到名称test
    • 下一行尝试运行test.aFunction()。中不存在这样的名称test。引发异常。

  • 定义的行def aFunction()永远不会执行,因为引发了异常。

Remove the import test2line, and run test2.pydirectly, and importing the function will work fine:

去掉那import test2行,test2.py直接运行,导入函数就可以了:

import test

test.aFunction()