python - 有没有办法使用 Python 自己的类来模拟“bool”或“NoneType”类型的对象?
问题描述
我正在设计一个 Python 库来促进对 JSON 文件的各种操作。
它的基本功能在于对象的继承,也就是说,有类JSONDict
, JSONList
, JSONStr
,JSONFloat
等从其父类dict
, list
, str
, float
... 继承并添加新的属性。
到目前为止没问题,因为通过子实例化 python 对象序列化是微不足道的。问题与JSONBool
对象有关JSONNone
,因为由于内部 Python 限制,您不能从 bool 和 NoneType 继承(它们是单例),所以我必须为它们定义自己的序列化程序,以便能够json.dumps
在 JSON 对象上使用。
但是,在外部应用程序中使用这个库时,往往不知道 JSON 文件中的某些字段将具有的值,而我真正不喜欢的是不同类型之间的行为不对称。例如:
data = {
"string": "str",
"bool": True,
"null": None
}
json_object = JSONObject(data) # load data dict as my custom JSONObject instance
>> json_object.get_key("string")
'str' # this is actually a JSONStr instance, therefore it is serializable
>> json_object.get_key("bool")
True # but this is a JSONBool instance, and we cannot use this result directly in external apps,
# we must serialize it as data.get_key("bool").json_decode in order to retrieve a real True value
我想要的是不必调用该json_decode
方法来序列化来自JSONBool
或JSONNone
实例的数据,我希望外部程序将它们视为所有意图bool
和NoneType
目的的类型。我希望这些结果可以立即重复使用,如果它们分别是bool
和的子实例,这将是可能的NoneType
。
无论如何要处理这个?也许某种内部的 Python 魔术方法?bool
或对 CPython 进行一些破解以消除单例对and的限制NoneType
?任何建议将不胜感激
解决方案
推荐阅读
- php - Codeception 验收测试报告覆盖率为 0%
- powershell - 带有通配符意外结果的测试路径
- hyperledger-composer - Windows 10 linux 子系统上的 Fabric-Composer?
- c++ - winapi 的 LoadImage() 总是返回 NULL
- javascript - 如何通过ajax将json对象附加到表中,并在jquery中有时间延迟?
- javascript - javascript文件代码在createElement附加时不起作用
- c++ - ESP 32 TCP 连接被对等方关闭
- c# - 在 C# 上控制来自 2 个不同表单的单个表单
- excel - POWER BI - RLS - 在 Excel 连接中分析
- c# - 我将如何构建这个数据库?