问题描述
- 在使用python
json.dumps()
方法输出dict格式内容:
class MyClass(dict):
def __init__(self):
...
json.dumps(super(MyClass, self), ensure_ascii=False)
- 运行时出现错误:
TypeError: Object of type super is not JSON serializable
问题分析
- python中
super
并非关键字,而是一个builtin
的一个class
,虽然dict本身时可以被json.dumps
的,但super
类dumps
方法并不认,所以导致了这个问题的发生。 - 查看
super
源码:
class super(object):
"""
super() -> same as super(__class__, <first argument>)
super(type) -> unbound super object
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type, type2) -> bound super object; requires issubclass(type2, type)
Typical use to call a cooperative superclass method:
class C(B):
def meth(self, arg):
super().meth(arg)
This works for class methods too:
class C(B):
@classmethod
def cmeth(cls, arg):
super().cmeth(arg)
"""
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __get__(self, *args, **kwargs): # real signature unknown
""" Return an attribute of instance, which is of type owner. """
pass
def __init__(self, type1=None, type2=None): # known special case of super.__init__
"""
super() -> same as super(__class__, <first argument>)
super(type) -> unbound super object
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type, type2) -> bound super object; requires issubclass(type2, type)
Typical use to call a cooperative superclass method:
class C(B):
def meth(self, arg):
super().meth(arg)
This works for class methods too:
class C(B):
@classmethod
def cmeth(cls, arg):
super().cmeth(arg)
# (copied from class doc)
"""
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
__self_class__ = property(lambda self: type(object))
"""the type of the instance invoking super(); may be None
:type: type
"""
__self__ = property(lambda self: type(object))
"""the instance invoking super(); may be None
:type: type
"""
__thisclass__ = property(lambda self: type(object))
"""the class invoking super()
:type: type
"""
- 可以看到,
__self__
变量为实际super所指向的class实例,这才是dumps
方法真正想要的内容。
解决方法
- 将代码修改如下即可成功运行:
json.dumps(super(MyClass.__self__, self), ensure_ascii=False)
如果对你有用的话随手点个赞再走吧~~