编写单独的 Reader/Writer 类的目的是支持不同的输出处理——写入控制台、写入字节、写入 JSON 字符串等等。重要的是每个类 Struct1、Struct2 等都知道哪些属性对于保存它们的状态很重要。这是 pickle 模块使用的理念。
class Struct1(object):
fields = ('a','b','c')
...
class Struct2(object):
fields = ('foo', 'bar', 'baz')
...
现在可以使用此元数据编写各种编写器类,而无需编写特定于类的代码:
class StructWriter(object):
packTypeMap = {int:'i', float:'f', str:'s'}
def write(self, obj):
fields = obj.fields
packstring = ''.join(packTypeMap[type(f)] for f in fields)
packargs = (getattr(obj,f) for f in fields)
return struct.pack(packstring, *packargs)
class DictWriter(object):
def write(self, obj):
return dict((f, getattr(obj,f)) for f in obj.fields)
class JSONWriter(object):
jsonTypeMap = {str:lambda s:"'"+s+"'"}
defaultJsonFunc = lambda x:str(x)
def write(self, obj):
# not really recommended to roll your own strings, but for illustration...
fields = obj.fields
outargs = (getattr(obj,f) for f in fields)
outvals = (jsonTypeMap.get(type(arg),defaultJsonFunc)(arg)
for arg in outargs)
return ('{' +
','.join("'%s':%s" % field_val for field_val in zip(fields, outvals))
'}')
class ZipJSONWriter(JSONWriter):
def write(self, obj):
import zlib
return zlib.compress(super(ZipJSONWriter,self).write(obj))
class HTMLTableWriter(object):
def write(self, obj):
out = "<table>"
for field in obj.fields:
out += "<tr><td>%s</td><td>%s</td></tr>" % (field, getattr(obj,field))
out += "</table>"
return out