Python:从导入的文件调用函数 [英] Python: calling function from imported file

查看:69
本文介绍了Python:从导入的文件调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

测试:

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

测试 2:

import test
aFunction()

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

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

from test import aFunction

还有:

from test import *

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

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

推荐答案

您正在创建循环导入.test.py 导入 test2.py 尝试导入 test.py.

You are creating a circular import. test.py imports test2.py which tries to import test.py.

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

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

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

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

运行 import test2 行.

  • test2 被编译并执行,并在sys.modules 中添加一个空模块对象.

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

运行 import test 行.

  • test 已经作为 sys.modules 中的一个模块存在,这个对象被返回并绑定到名称 test.
  • test is already present as a module in sys.modules, this object is returned and bound to the name test.

下一行尝试运行 test.aFunction().test 中不存在这样的名称.引发异常.

A next line tries to run test.aFunction(). No such name exists in test. An exception is raised.

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

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

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

Remove the import test2 line, and run test2.py directly, and importing the function will work fine:

import test

test.aFunction()

这篇关于Python:从导入的文件调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆