Python 名称错误:全局名称';测试';没有定义
嗨,我有两个python文件:project.py和test.py 我正在尝试将变量从test.py导入project.py 代码如下: test.pyPython 名称错误:全局名称';测试';没有定义,python,python-2.7,class,module,Python,Python 2.7,Class,Module,嗨,我有两个python文件:project.py和test.py 我正在尝试将变量从test.py导入project.py 代码如下: test.py newton = 0 def apple(n): global newton n = newton time.sleep(15) n = n + 1 return 在project.py中 from test import * class search(object): def __init
newton = 0
def apple(n):
global newton
n = newton
time.sleep(15)
n = n + 1
return
在project.py中
from test import *
class search(object):
def __init__(self):
self.servo = test.apple(n)
def run(self):
while (self.servo < 1):
print "hELLO"
来自测试导入的*
类搜索(对象):
定义初始化(自):
self.servo=test.apple(n)
def运行(自):
而(自伺服<1):
打印“你好”
当我运行project.py时,我得到了name错误:project.py self.servo=test.apple(n)中未定义全局名称“test”
有人能指出我代码中的错误吗 您希望
test
是什么
来自测试导入的*
这将加载test中找到的所有内容,在本例中为test.py。这样将把以下内容加载到全局命名空间中:
(值为newton
)0
(一种功能)apple
test
的符号,因此当您在\uuuuu init\uuuu
方法中调用test.apple
时,您会得到一个namererror
如果要将test.py作为test
导入,则只需导入模块本身,而不需要从模块导入内容:
import test
@Dan Lowe我删除了test.apple(n)中的测试,但我仍然得到一个名称错误,但这次使用了“n”。事实上,我不太确定如何让self.servo承担起n@Sevyon除非在project.py的第4行中使用
n
,否则不会提到它。它不存在。我认为您可能需要更多地阅读有关变量作用域以及如何在Python中构造类的内容。