我正在尝试建立一个简单的学生数据库(姓名和年龄)。
当我试图删除一个兴奋的学生并打印数据库时,它打印我
import pickle
class data_base:
data={}
class __metaclass__(type):
def __iter__(self):
for attr in dir(data_base):
if not attr.startswith("__"):
yield attr
def __init__(self):
self.write("")
def write(self,my_data):
pickle.dump( my_data, open( "database.p", "wb" ) )
def read(self):
return pickle.load( open( "database.p", "rb" ) )
def delete_student(self):
#delete key and value
to_delete=raw_input("who do you want to delete? ")
my_data=self.read()
if to_delete in my_data.__iter__():
my_data.pop(to_delete)
self.write(data_base)
else:
print "no such student"
def clear_data_base(self):
#delete data baase
self.write("")
def main():
first_data={"ben":10,"dan":6}
my_data_base=data_base()
my_data_base.clear_data_base()
my_data_base.write(first_data)
print my_data_base.read()
my_data_base.delete_student()
print my_data_base.read()
,但如果我试图删除一个不存在的学生,它会打印出数据库。
==
答案 0 :(得分:0)
问题在于:
self.write(data_base)
您已经将类对象腌制而不是您读入的实例my_data
。将您的方法更改为
def delete_student(self):
#delete key and value
to_delete=raw_input("who do you want to delete? ")
my_data=self.read()
if to_delete in my_data.__iter__():
my_data.pop(to_delete)
self.write(my_data)
else:
print "no such student"