gpt4 book ai didi

python - Python中用户类的序列化

转载 作者:行者123 更新时间:2023-11-28 17:03:54 25 4
gpt4 key购买 nike

我想使用对象的类型作为字典键,最好将此类字典序列化为 JSON 字符串。可以对其进行反序列化,然后使用简单的“if SomeType in SomeDictionary”检查。

演示该问题的最小代码示例:

import json

class Cat():
def __init__(self, name):
self.name = name

class Dog():
def __init__(self, name):
self.name = name

pets = dict()
pets[Cat] = Cat("Tom")
pets[Dog] = Dog("Rex")

print(pets.keys())
print(json.dumps(pets))

我得到错误:

dict_keys([<class '__main__.Cat'>, <class '__main__.Dog'>])
Traceback (most recent call last):
File "python", line 17, in <module>
TypeError: keys must be a string

第 17 行表示带有“print(json.dumps(pets))”的行。

是否可以在 Python 中实现这种行为?

最佳答案

替代方案

pets = {"Tom" : Cat("Tom"), "Rex" : Dog("Rex")}
print(pets.keys())
print(json.dumps(pets))

最后,如果不循环遍历所有值,就无法说“字典中有猫或狗”

关于python - Python中用户类的序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52517662/

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