0

也许更多的是基于面向对象的编程 -

将通用 TLV 定义为

 class MYTLV(Packet):
       fields_desc = [
             ByteEnumField("type", 0x1, defaultTLV_enum),
             FieldLenField("length", None, fmt='B', length_of="value"),
             StrLenField("value", "ABCDEF", length_from=lambda x:x.length)
       ]

我有许多相同形式但类型不同的 TLV。我怎样才能有更好的代码来减少代码中的这种情况

     class newTLV(MYTLV):
          some code to say or initiaze type field of this newTLV to newTLV_enum
     ....

所以以后我可以用作 -

     PacketListField('tlvlist', [], newTLV(fields.type=newTLV_enum))

除了类型字段的字典外,所有 TLV 都是相同的。

    class MYTLV1(Packet):
       fields_desc = [
             ByteEnumField("type", 0x1, TLV1_enum),
             FieldLenField("length", None, fmt='B', length_of="value"),
             StrLenField("value", "ABCDEF", length_from=lambda x:x.length)
       ]
   class MYTLV2(Packet):
       fields_desc = [
             ByteEnumField("type", 0x1, TLV2_enum),
             FieldLenField("length", None, fmt='B', length_of="value"),
             StrLenField("value", "ABCDEF", length_from=lambda x:x.length)
       ]
4

1 回答 1

2

你可以这样做:

base_fields_desc = [
    FieldLenField("length", None, fmt='B', length_of="value"),
    StrLenField("value", "ABCDEF", length_from=lambda x:x.length)
]

def fields_desc_with_enum_type(enum_type):
    fields_desc = base_fields_desc[:]
    fields_desc.insert(0, ByteEnumField("type", 0x1, enum_type))
    return fields_desc


class MYTLV1(Packet):
    fields_desc = fields_desc_with_enum_type(TLV1_enum)

class MYTLV2(Packet):
    fields_desc = fields_desc_with_enum_type(TLV2_enum)
于 2015-05-12T02:31:57.467 回答