任何更好的代码来定义针对不同类型启动的通用 TLV

Any better code to define generic TLV initiatzed to different types

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

将通用 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
     ....

所以以后我可以使用 as -

     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)
       ]

你可以这样做:

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)