python - NameError:未定义名称“类”
问题描述
我写了一个类(搜索器)用于在数据库中搜索一串单词,但是当我想执行我的脚本时,我得到了这个错误:
NameError:名称“搜索者”未定义
我的代码:
class searcher:
def __init__(self, dbname):
self.con = sqlite3.connect(dbname)
def __del__(self):
self.con.close()
def getmatchrows(self,q):
fieldlist = 'w0.urlid'
tablelist = ''
clauselist = ''
words = q.split(' ')
tablenumber = 0
wordids = []
for word in words:
wordrow = self.con.execute("select rowid from wordlist where word = '%s'" %word).fetchone()
if wordrow !=None:
wordid = wordrow[0]
wordids.append(wordid)
if tablenumber > 0:
tablelist+=','
clauselist+=' and '
clauselist+='w%d.urlid=w%d.urlid and ' % (tablenumber -1, tablenumber)
fieldlist+=',w%d.location'% tablenumber
tablelist+='wordlocation w%d'% tablenumber
clauselist+='w%d.wordid = %d' % (tablenumber,wordid)
tablenumber+=1
query = 'select %s from %s where %s' % (fieldlist,tablelist,clauselist)
cur = self.con.execute(query)
rows = [row for row in cur]
return rows,wordids
wordsearch = searcher('searchindex.db')
print wordsearch.getmatchrows('indie music')
我究竟做错了什么?!!
解决方案
代码的最后两行是缩进的,因此它们属于该class searcher:
块。但是,searcher
该类在此块结束之前不存在,因此尝试引用searcher
inwordsearch = searcher('searchindex.db')
失败。
取消最后两行。
推荐阅读
- c++ - 如何在 C++ 中打印具有第一个和第二个 2 类的对向量?
- google-cloud-firestore - Firestore 是否会清除自己的文档缓存?
- python - 通过在 Python 中从 Popen 读取字节输入将 MJPEG 转换为 JPEG
- vb.net - 如何将两个数组添加在一起visual basic
- r - 随机化宏
- python - 跨度类中的Python解析字符串
- android - 如何从 Firebase Storage 获取 URL 并将其发送到数据库?
- c# - JsonConvert.DeserializeObject
() 正在添加一组额外的花括号 - java - 从 maven-Selenium 测试中获取初始化程序错误中的异常
- ios - 更新到 Xcode 11.4、Swift 5.2 后 Swift -Enum 重新声明错误