通過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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM