简体   繁体   English

如何修复名称未在 Python 中定义

[英]How to fix name is not defined in Python

I am running a python project like this:我正在运行这样的python项目:

project
  Test.py
  COMMON.py
  SYSTEM.py
  PTEST1
    Hello.py

when run the code "Test.py" it will show NameError, I am not sure why?当运行代码“Test.py”时,它会显示 NameError,我不知道为什么?

But if I replaced the "from SYSTEM import *" with "from COMMON import *" in Test.py and PTEST1/Hello.py, it works as expect.但是,如果我将 Test.py 和 PTEST1/Hello.py 中的“from SYSTEM import *”替换为“from COMMON import *”,它会按预期工作。

#Test.py is like this:

from SYSTEM import *
myvalue.Hello.printf()

# COMMON.py is like this:

myvalue = lambda: None
from PTEST1.Hello import Hello
myvalue.Hello = Hello

# SYSTEM.py is like this:

from COMMON import *
#PTEST1/Hello.py
from SYSTEM import *

class Hello():   
    @staticmethod
    def printf():
        print("Hello1")
        print(vars(myvalue))

I expect there is no "NameError" by not changing import code.我希望通过不更改导入代码不会出现“NameError”。 BTW, my python is 3.6+顺便说一句,我的蟒蛇是 3.6+

Good practice is to give filenames in lowercase.好的做法是以小写形式给出文件名。

It looks like you are creating a Python project under project/ .看起来您正在project/下创建一个 Python 项目。 Any directory needs to have a file __init__.py in every directory in order for it to be discovered in Python.任何目录都需要在每个目录中有一个文件__init__.py才能在 Python 中被发现。

You then need to refer to modules by their full name (not relative naming).然后您需要通过它们的全名(而不是相对命名)来引用模块。

So the directory structure should be:所以目录结构应该是:

project/
  __init__.py
  test.py
  common.py
  system.py
  ptest1/
    __init__.py
    hello.py

Every time you refer to file you should give the full path.每次引用文件时,都应该提供完整路径。

# import everything from hello.py
from project.ptest1.hello import *

# import everything from common.py
from project.common import *

# import everything from system.py
from project.system import *

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

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