如何使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__)
我试图理解,除了这个名字之外,这些类之间是否有任何区别?如果我在声明变量"value"时使用或不使用__init __()函数会有什么不同吗?
class WithClass ():
def __init__(self):
self.value = "Bob"
def my_func(self):
print(self.value)
class WithoutClass ():
value = "Bob"
def my_func(self):
print(self.value)
Run Code Online (Sandbox Code Playgroud)
我主要担心的是,我将以一种方式使用它,因为这将导致我的问题进一步发展(目前我使用init调用).
可能重复:
Python可序列化对象json
我需要知道如何将动态python对象转换为JSON.该对象必须能够具有多个对象子对象.例如:
class C(): pass
class D(): pass
c = C()
c.dynProperty1 = "something"
c.dynProperty2 = { 1, 3, 5, 7, 9 }
c.d = D()
c.d.dynProperty3 = "d.something"
# ... convert c to json ...
Run Code Online (Sandbox Code Playgroud)
使用python 2.6以下代码:
import json
class C(): pass
class D(): pass
c = C()
c.what = "now?"
c.now = "what?"
c.d = D()
c.d.what = "d.what"
json.dumps(c.__dict__)
Run Code Online (Sandbox Code Playgroud)
产生以下错误:
TypeError: <__main__.D instance at 0x99237ec> is not JSON serializable
Run Code Online (Sandbox Code Playgroud)
我不知道用户可能会放入哪些类型的子对象c.是否存在足够智能的解决方案来检测属性是否为对象并__dict__自动解析?
更新以包括子对象 …
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) 我正在尝试使用JSON(使用simplejson)序列化python对象列表,并且得到对象"不是JSON可序列化"的错误.
该类是一个简单的类,其字段只有整数,字符串和浮点数,并且从一个父超类继承类似的字段,例如:
class ParentClass:
def __init__(self, foo):
self.foo = foo
class ChildClass(ParentClass):
def __init__(self, foo, bar):
ParentClass.__init__(self, foo)
self.bar = bar
bar1 = ChildClass(my_foo, my_bar)
bar2 = ChildClass(my_foo, my_bar)
my_list_of_objects = [bar1, bar2]
simplejson.dump(my_list_of_objects, my_filename)
Run Code Online (Sandbox Code Playgroud)
其中foo,bar是我上面提到的简单类型.唯一棘手的问题是ChildClass有时会有一个字段引用另一个对象(不是ParentClass或ChildClass的类型).
使用simplejson将此序列化为json对象的最简单方法是什么?将其序列化为字典是否足够?简单地为ChildClass 编写一个dict方法是最好的方法吗?最后,引用另一个对象的字段是否会使事情变得复杂化?如果是这样,我可以重写我的代码只在类中有简单的字段(如字符串/浮点数等)
谢谢.