如何解决Python搁置不保存嵌套键
我正在使用 saveSign = () => {
this.ref.current.saveImage();
}
模块来保存一些 Python 对象(示例中的字符串)。
当我尝试将对象保存为嵌套键时,它没有被保存。
shelve
代码应该打印:
class Car:
def __init__(self,ID):
self.id = ID
def save_to_shelf(self):
with shelve.open('shelf') as shelf:
if not shelf.get('users'):
shelf['users'] = {}
print(shelf['users'])
try:
shelf['users'][self.id] = "hello"
except Exception as e:
print(e)
print('saved')
print(shelf['users'])
car = Car(123)
car.save_to_shelf()
但它会打印:
{}
saved
{123: hello}
意思是它没有被保存
如果我打印键的值,它会给出 {}
saved
{}
KeyError
shelf['users'][self.id] = "hello"
print(shelf['users'][self.id])
如果我在保存时执行以下操作,我可以保存它 而不是
Traceback (most recent call last):
File "P:/Python practice/Shelll/main.py",line 3,in <module>
car.save_to_shelf()
File "P:/Python practice/Shelll\db.py",line 20,in save_to_shelf
print(shelf['users'][self.id])
KeyError: '123'
这有效
with shelve.open('shelf') as shelf:
shelf['users'][self.id] = "hello"
我想了解这背后的原因。据我所知, with shelve.open('shelf') as shelf:
USERS = shelf['users']
USERS[self.id] = self.id
shelf['users'] = USERS
# or this works
# with shelve.open('shelf') as shelf:
# shelf['users'] = {self.id:"hello"}
对象用作字典。所以我之前保存的方式应该有效,但没有。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。