Python 永久存储要在dict中使用的值
我的Order类中有一个dictionaryPython 永久存储要在dict中使用的值,python,python-3.x,Python,Python 3.x,我的Order类中有一个dictionaryself.total=defaultdict(int),用于输入和打印在我的订购系统中订购的每个项目的总计。对象存储为 coffee_available=[Coffee(1, "1: Flat White", 3.50), Coffee(2, "2: Long Black", 3.50), Coffee(3, "3: Cappuccino", 4.00), Coffee(4,
self.total=defaultdict(int)
,用于输入和打印在我的订购系统中订购的每个项目的总计。对象存储为
coffee_available=[Coffee(1, "1: Flat White", 3.50),
Coffee(2, "2: Long Black", 3.50),
Coffee(3, "3: Cappuccino", 4.00),
Coffee(4, "4: Espresso", 3.25),
Coffee(5, "5: Latte", 3.50)]
`
我对这些对象“排序”的方式是通过调用order类中的函数
def order(self, order_amount, coffee_id):
self.total[coffee_id] += order_amount
我使用order类中的另一个函数打印每个项目类型及其各自的订单金额
def print_order(self):
print(" ")
print("Coffee Type\t\tAmount of Times ordered")
print("-----------\t\t-----------------------")
for coffee in coffee_available:
print("{}\t- - -\t {} ".format(coffee.coffee_type, self.total[coffee.coffee_id]))
这与每次代码在同一会话中运行时一样有效,每次它都存储
订单金额
值并正确显示,唯一的问题是,如果我终止程序,它不会存储下次打开时的数据。如果我要永久存储数据,我将如何做?我应该永久存储什么?因此,您可以使用pickle
将任何python
对象持久化到文件中。因此,我们假设您想要持久化总数
import pickle
# total is a dictionary
# to store it in a file
with open('total_dictionary.pickle', 'wb') as handle:
pickle.dump(total, handle)
# lets say program terminated here
现在,
因此,您的order
方法更新您的self.total
和print\u order
只需查看即可。因此,基本上您需要在每次更新(order
call)之后存储self.total
。并且,在您第一次声明self.total
的类的初始值设定项中,您需要使用从pickle文件(如果存在)加载的字典来初始化self.total
更具体一点说:
import pickle
..
def order(self, order_amount, coffee_id):
self.total[coffee_id] += order_amount
with open('total_dictionary.pickle', 'w') as handle:
pickle.dump(total, handle)
在类的顺序的初始值设定项中
import os
..
def __init__(self):
...
if os.path.exists("total_dictionary.pickle"):
with open('total_dictionary.pickle', 'r') as handle:
total = pickle.load(handle)
else:
total = defaultdict(int)
...
您可以删除/删除总字典。pickle
重置
希望它有帮助:)pythonpickle
库是关键:因此我使用pickle的方法是将值存储在self.total dict中,并在以后需要调用order函数时调用它。order
函数更新self.total
和print\u order
访问它。因此,您所需要做的就是:在每次更新调用之后,即使用pickle将total
字典存储在文件中。在类的初始值设定项中,确保如果存在pickle文件,则使用该字典初始化total。酷?谢谢你的帮助,现在可以用了。它不存储第一个订单,但这很好。您的更新引发此错误“AttributeError:模块“ntpath”没有更新属性“exist”。错误在于函数是os.path.exists
而不是os.path.exist
。复数“s”。还要确保已导入操作系统模块。
import os
..
def __init__(self):
...
if os.path.exists("total_dictionary.pickle"):
with open('total_dictionary.pickle', 'r') as handle:
total = pickle.load(handle)
else:
total = defaultdict(int)
...