首页 > 解决方案 > 有没有办法使用 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方法来序列化来自JSONBoolJSONNone实例的数据,我希望外部程序将它们视为所有意图boolNoneType目的的类型。我希望这些结果可以立即重复使用,如果它们分别是bool和的子实例,这将是可能的NoneType

无论如何要处理这个?也许某种内部的 Python 魔术方法?bool或对 CPython 进行一些破解以消除单例对and的限制NoneType?任何建议将不胜感激

标签: pythonjsoncpython

解决方案


推荐阅读