简体   繁体   中英

NameError: global name is not defined

I'm using Python 2.6.1 on Mac OS X.

I have two simple Python files (below), but when I run

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. ;)

File 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

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. 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.' to your function,class etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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