【发布时间】:2018-05-12 00:06:40
【问题描述】:
我在 Python 3.5 中有这个类:
class DataPoint(object):
def __init__(self, time, value):
self.time = time
self.value = value
当我尝试从一个实例创建一个 JSon 时,这样做:
json.dumps( intance_of_datapoint )
我得到错误:
TypeError: < DataPoint object at 0x0123 > is not JSon Serializable
所以我尝试改进覆盖 repr 方法的类,如下所示:
class DataPoint(object):
def __init__(self, time, value):
self.time = time
self.value = value
def __str__(self):
return json.dumps(self.__dict__)
__repr__ = __str__
通过这样做,我得到:
TypeError: {"value":52.29, "time":1} is not JSon serializable.
你们能帮我理解为什么吗? 我在这里很迷茫。
【问题讨论】: