Python 模块导入:NameError:名称未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19712395/
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
module import: NameError: name is not defined
提问by Val
How do I define the function in the importer so that it is visible inside imported? I tried this
我如何在导入器中定义函数,以便它在导入的内部可见?我试过这个
importer.pyis
importer.py是
def build():
print "building"
build()
import imported
Whereby, imported.pyis simply
由此,imported.py简直
build()
Yet, this fails
然而,这失败了
building
Traceback (most recent call last):
File "C:\Users\valentin\Desktop\projects\maxim\miniGP\b01\evaluator\importer.py", line 6, in <module>
import imported
File "C:\Users\valentin\Desktop\projects\maxim\miniGP\b01\evaluator\imported.py", line 1, in <module>
build()
NameError: name 'build' is not defined
UpdateAfter I have got the response to make the circular import, so that import and imported depend on each other, I feel that I need to make clear that this is not always good. My purpose is to specify some common strategy in the imported module. It will use some user-defined functions, e.g. build. User defines the necessary function(s) and calls the strategy. The point is that the shared strategy must not depend on specific user definitions. I believe that in place of import, I need something like evaluate(imported.py), which I believe is a basic function in any script language, including Python. irc://freenode/python insists that I must use importbut I do not understand how.
更新得到响应后进行循环导入,让导入和导入相互依赖,我觉得我需要澄清一下,这并不总是好的。我的目的是在导入的模块中指定一些常用的策略。它将使用一些用户定义的函数,例如build. 用户定义必要的函数并调用策略。关键是共享策略不能依赖于特定的用户定义。我相信,代替import,我需要类似的东西evaluate(imported.py),我相信这是任何脚本语言(包括 Python)中的基本功能。irc://freenode/python 坚持我必须使用,import但我不明白如何使用。
采纳答案by Val
回答by SujitS
importer.py
进口商.py
def build():
print("building")
build() #this extra call will print "building" once more.
imported.py
导入的.py
from importer import build
build()
Note that both importer.py and imported.py must be in same directory. I hope this solve your problem
请注意,importer.py 和imported.py 必须在同一目录中。我希望这能解决你的问题
回答by msw
Imports are not includes: they are idempotent and should always be at the top of a module.
导入不是包含:它们是幂等的,应该始终位于模块的顶部。
There is no circularity; once import foois seen, further instances of import foowill not load the module again.
没有圆形;一旦import foo看到,进一步的实例import foo将不会再次加载模块。
You are getting the NameError because in the context of imported.py, there is no name build, it is known as importer.build().
您收到 NameError 是因为在 import.py 的上下文中,没有 name build,它被称为importer.build().
I have no idea what you are trying to do with code as oddly structured as that.
我不知道你想用结构如此奇怪的代码做什么。

