gpt4 book ai didi

python - 结构打包/拆包类设计

转载 作者:行者123 更新时间:2023-11-30 23:38:53 26 4
gpt4 key购买 nike

我正在实现二进制文件格式(~15 种不同的结构)读取器/写入器,但我有点进退两难,应该使用哪种设计模式。

  1. 每个结构体都包含打包/解包的方法:

    class Struct1:  
    def pack():
    struct.pack(self.foo)
    ...
    def unpack():
    self.foo = struct.unpack()
    ...
    class Struct2:
    def pack():
    struct.pack(self.foo)
    ...
    def unpack():
    self.foo = struct.unpack()
    ...
    ...

    对比

  2. 每个结构都有一个具有读/写方法的 Reader/Writer 类:

    class Reader:
    def read_struct1():
    s = Struct1()
    s.foo = struct.unpack()
    ...
    return s
    def read_struct2():
    s = Struct2()
    s.foo = struct.unpack()
    ...
    return s
    ...
    class Writer:
    def write_struct1(s):
    struct.pack(s.foo)
    ...
    def write_struct2(s):
    struct.pack(s.foo)
    ...
    ...

最佳答案

编写单独的 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

关于python - 结构打包/拆包类设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14055859/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com