简体   繁体   English

Python中用户类的序列化

[英]Serialization of the user Class in Python

I want to use the type of the object as a dictionary key with the possibility to serialize such dictionary into JSON string, preferably. 我想使用对象的类型作为字典键,可以将这样的字典序列化为JSON字符串。 With the possibility to de-serialize it and then use simple "if SomeType in SomeDictionary" check. 可以对其进行反序列化,然后使用简单的“if SomeType in SomeDictionary”进行检查。

The minimum code example that demonstrates the issue: 演示此问题的最小代码示例:

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))

I get the error: 我收到错误:

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

The line 17 indicates the line with "print(json.dumps(pets))". 线17表示具有“print(json.dumps(pets))”的行。

Is it possible to implement such behavior in Python? 是否可以在Python中实现此类行为?

You can try this: 你可以试试这个:

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))

Alternative solution 替代方案

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

In the end, there's no way to say "is there a cat or dog in the dictionary" without looping over all the values 最后,没有办法在没有循环所有值的情况下说“字典中是否有猫或狗”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM