Python NameError:未定义全局名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3977167/
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
NameError: global name is not defined
提问by Wizzard
I'm using Python 2.6.1 on Mac OS X.
我在 Mac OS X 上使用 Python 2.6.1。
I have two simple Python files (below), but when I run
我有两个简单的 Python 文件(如下),但是当我运行时
python update_url.py
I get on the terminal:
我在终端上:
Traceback (most recent call last):
File "update_urls.py", line 7, in <module>
main()
File "update_urls.py", line 4, in main
db = SqliteDBzz()
NameError: global name 'SqliteDBzz' is not defined
I tried renaming the files and classes differently, which is why there's x and z on the ends. ;)
我尝试以不同的方式重命名文件和类,这就是为什么末尾有 x 和 z 的原因。;)
File sqlitedbx.py
文件 sqlitedbx.py
class SqliteDBzz:
connection = ''
curser = ''
def connect(self):
print "foo"
def find_or_create(self, table, column, value):
print "baar"
File update_url.py
文件 update_url.py
import sqlitedbx
def main():
db = SqliteDBzz()
db.connect
if __name__ == "__main__":
main()
采纳答案by SilentGhost
You need to do:
你需要做:
import sqlitedbx
def main():
db = sqlitedbx.SqliteDBzz()
db.connect()
if __name__ == "__main__":
main()
回答by joaquin
try
尝试
from sqlitedbx import SqliteDBzz
回答by kfirbreger
Importing the namespace is somewhat cleaner. Imagine you have two different modules you import, both of them with the same method/class. Some bad stuff might happen. I'd dare say it is usually good practice to use:
导入命名空间更简洁一些。想象一下,您导入了两个不同的模块,它们都具有相同的方法/类。可能会发生一些不好的事情。我敢说使用以下方法通常是个好习惯:
import module
over
超过
from module import function/class
回答by devsaw
That's How Python works. Try this :
这就是 Python 的工作原理。尝试这个 :
from sqlitedbx import SqliteDBzz
Such that you can directly use the name without the enclosing module.Or just import the module and prepend 'sqlitedbx.' to your function,class etc
这样您就可以直接使用名称而无需封闭模块。或者只需导入模块并在前面加上“sqlitedbx”。到您的函数、类等

