简体   繁体   English

NameError:全局名称“测试”未定义

[英]NameError: Global Name 'test' is not defined

Hi I have two python files: project.py and test.py. 嗨,我有两个python文件:project.py和test.py。

I am trying to import variable from test.py to project.py. 我试图将变量从test.py导入到project.py。

Following is the code: 以下是代码:

test.py test.py

newton = 0
def apple(n):
    global newton
    n = newton
    time.sleep(15)
    n = n + 1
    return

and in project.py 并在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"

When I run project.py I get NameError: Global name 'test' is not defined in project.py self.servo = test.apple(n) 当我运行project.py时,我得到NameError:在project.py中未定义全局名称“ test” self.servo = test.apple(n)

Can anyone point out what is wrong in my code? 谁能指出我的代码出了什么问题?

What are you expecting test to be? 您期望test是什么?

from test import *

This will load everything found in test, which in this case is test.py. 这将加载测试中找到的所有内容,在本例中为test.py。 So that will load the following into the global namespace: 这样会将以下内容加载到全局名称空间中:

  • newton (with a value of 0 ) newton (值为0
  • apple (a function) apple (功能)

It does not load any symbol named test , so when you call test.apple in your __init__ method, you get a NameError . 它不会加载任何名为test符号,因此,当您在__init__方法中调用test.apple时,会出现NameError

If you want to import test.py as test , you instead need to just import the module itself, not import things from the module: 如果要将test.py导入为test ,则只需导入模块本身,而不是模块中导入内容:

import test

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM