通过Python中的class模拟结构体

Python不支持结构体,但是可以通过创建类来存储结构化数据

class Command(object):
    def __init__(self, addr, length, format, bits, bytes):
        self.addr = addr
        self.length = length
        self.format = format
        self.bits = bits
        self.bytes = bytes

x01 = Command(0x01, 1, 'hex', None, None)
x78 = Command(0x78, 1, 'hex', [7, 6, 5, 4, 3, 2, 1, 0], None)
x79 = Command(0x79, 2, 'hex', [7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8], None)

将多个实例放入列表中,就可以通过循环对每个实例中的数据进行访问了

    commands = [x01, x78, x79, x7a, x7b, x7c, x7d, x7e, x80,x81, xe3, xe6,
                x88, x89, x8a, x8b , x8c, x8d, x8e, x8f, x90, x96, x97]
    for index in commands:
        print(index.addr, index.bits)

 

posted @ 2021-06-05 16:59  *雷子*  阅读(1265)  评论(0编辑  收藏  举报