简体   繁体   English

NameError:未定义全局名称

[英]NameError: global name is not defined

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()

You need to do: 你需要这样做:

import sqlitedbx

def main():
    db = sqlitedbx.SqliteDBzz()
    db.connect()

if __name__ == "__main__":
    main()

尝试

from sqlitedbx import SqliteDBzz

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

That's How Python works. 这就是Python的工作方式。 Try this : 尝试这个 :

from sqlitedbx import SqliteDBzz

Such that you can directly use the name without the enclosing module.Or just import the module and prepend 'sqlitedbx.' 这样你就可以直接使用没有封闭模块的名称。或者只需导入模块并添加'sqlitedbx'。 to your function,class etc 你的功能,课程等

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

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