[英]Serialization of the user Class in Python
我想使用對象的類型作為字典鍵,可以將這樣的字典序列化為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中實現此類行為?
你可以試試這個:
import json
class Cat():
def __init__(self, name):
self.name = name
class Dog():
def __init__(self, name):
self.name = name
pets = dict()
pets[str(Cat)] = Cat("Tom").__dict__ #he can get the value using pets[str(Cat)] or pets.get(str(Cat),None))
pets[str(Dog)] = Dog("Rex").__dict__
print(pets.keys())
print(json.dumps(pets))
替代方案
pets = {"Tom" : Cat("Tom"), "Rex" : Dog("Rex")}
print(pets.keys())
print(json.dumps(pets))
最后,沒有辦法在沒有循環所有值的情況下說“字典中是否有貓或狗”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.