gpt4 book ai didi

python - 在python中使用自定义命令制作数据库

转载 作者:搜寻专家 更新时间:2023-10-30 19:46:07 24 4
gpt4 key购买 nike

我正在尝试使用 Python 创建一个简单的本地数据库,我可以在其中设置值、获取值等,但我不断收到此错误:

#Simple Database
#Functions include Set[name][value]
# Get[name]
# Unset[name]
# Numequalto[value]
# End
# Begin, Rollback, Commit

varlist = []
ops = []
class item:
def __init__(self,name,value):
self.name = name
self.value = value
class db:
def __init__(self):
self.varlist = []
self.ops = []
def Set(self,nm,val):
changed = False #Bool for keeping track of update
for item in varlist: #run through current list
if item.name == nm: #If the name is found
item.value = val #update the value
changed = True #found it
break #exit if found
if not changed:
newitem = item() #Create a new one and append it
newitem.name = nm
newitem.value = val
varlist.append(newitem)
def Get(key):
for item in varlist:
if item.name == key:
return item.value
break

def Unset(key):
for item in varlist:
if item.name == key:
item.value = -1
break

def Numequalto(key):
count = 0
for item in varlist:
if item.value == key:
count+=1
return count

def main():
newdb = db()
varlist=[]
comm = "" #prime it
while comm.lower() != "end":
comm = input("Command: ")
if comm.lower() == "begin":
print("----SESSION START---")
while comm.lower() != "end":
comm = input("Command: ")
part = []
for word in comm.split():
part.append(word.lower())
print(part)
if part[0].lower()=="set":
newdb.Set(part[1],part[2])
print(varlist)
elif part[0].lower()=="get":
gotten = Get(part[1])
print(gotten)
elif part[0].lower()=="unset":
Unset(part[1])
elif part[0].lower()=="numequalto":
numequal = Numequalto(part[1])
print(numequal)
print("Finished")
else:
print("--ERROR: Must BEGIN--")


if __name__ == "__main__":
main()

当我运行它并尝试使用命令在我的列表中创建一个新项目时

set a 25

我收到这个错误:

Traceback (most recent call last):
File "/Volumes/CON/LIFE/SimpleDatabase.py", line 81, in <module>
main()
File "/Volumes/CON/LIFE/SimpleDatabase.py", line 65, in main
newdb.Set(part[1],part[2])
File "/Volumes/CON/LIFE/SimpleDatabase.py", line 27, in Set
newitem = item() #Create a new one and append it
UnboundLocalError: local variable 'item' referenced before assignment

任何帮助将不胜感激。我是 Python 的新手

最佳答案

线

for item in varlist: 

用局部变量隐藏类 item。因此,当您到达 item() 时,它认为您正在尝试调用局部变量而不是类。你可以看出你的类 item 永远不会被构造,因为它会失败,因为你没有向 __init__

传递任何参数

此外,您确实应该将您的类命名为Item。一旦我这样做了,我就得到了预期的构造函数错误。

关于python - 在python中使用自定义命令制作数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16203229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com