如何使Python类可序列化?
一个简单的课程:
class FileItem:
def __init__(self, fname):
self.fname = fname
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能得到输出:
>>> import json
>>> my_file = FileItem('/foo/bar')
>>> json.dumps(my_file)
TypeError: Object of type 'FileItem' is not JSON serializable
Run Code Online (Sandbox Code Playgroud)
没有错误(__CODE__)
我正在尝试创建类实例的JSON字符串表示并且有困难.假设这个类是这样构建的:
class testclass:
value1 = "a"
value2 = "b"
Run Code Online (Sandbox Code Playgroud)
对json.dumps的调用是这样的:
t = testclass()
json.dumps(t)
Run Code Online (Sandbox Code Playgroud)
它失败并且告诉我测试类不是JSON可序列化的.
TypeError: <__main__.testclass object at 0x000000000227A400> is not JSON serializable
Run Code Online (Sandbox Code Playgroud)
我也尝试过使用pickle模块:
t = testclass()
print(pickle.dumps(t, pickle.HIGHEST_PROTOCOL))
Run Code Online (Sandbox Code Playgroud)
它提供类实例信息,但不提供类实例的序列化内容.
b'\x80\x03c__main__\ntestclass\nq\x00)\x81q\x01}q\x02b.'
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
class gpagelet:
"""
Holds 1) the pagelet xpath, which is a string
2) the list of pagelet shingles, list
"""
def __init__(self, parent):
if not isinstance( parent, gwebpage):
raise Exception("Parent must be an instance of gwebpage")
self.parent = parent # This must be a gwebpage instance
self.xpath = None # String
self.visibleShingles = [] # list of tuples
self.invisibleShingles = [] # list of tuples
self.urls = [] # list of string
class gwebpage:
"""
Holds all the datastructure after …Run Code Online (Sandbox Code Playgroud)