You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中能否将类内多个bytearray封装为数组简化拼接操作?

解决方案:简化Bytearray拼接并保留单独操作能力

Absolutely you can do this—here's a clean way to streamline your buffer creation while keeping full access to individual bytearray properties:

Step 1: Add an ordered sequence of your header bytearrays

First, define a class-level list that holds references to your msg_hdr_* attributes in the exact order you want them concatenated. This keeps the sequence reusable and tied to the class structure:

class message():
    msg_hdr_ONE = bytearray(b'\x00')
    msg_hdr_TWO = bytearray(b'\x00')
    msg_hdr_THREE = bytearray(b'\x00\x00')
    msg_hdr_FOUR = bytearray(b'\x00\x00')
    
    # Ordered list of headers (matches your original extend order)
    _header_sequence = [msg_hdr_ONE, msg_hdr_TWO, msg_hdr_THREE, msg_hdr_FOUR]
    
    def createBuffer(self):
        self.byteArrays = bytearray()
        # Single extend call to concatenate all headers
        self.byteArrays.extend(b''.join(self._header_sequence))
        return self.byteArrays  # Fixed: original code missed `self.` here

Step 2: Why this works

  • b''.join(self._header_sequence) takes all your bytearrays (which are bytes-compatible) and concatenates them into a single bytes object in one go. Passing this to extend() fills your buffer in a single operation.
  • Crucially, msg_hdr_THREE and other attributes remain fully accessible for direct modification. For example:
    myMessage = message()
    myMessage.msg_hdr_THREE[1] = 0xFF  # Modify individual byte
    buffer = myMessage.createBuffer()  # Buffer now includes your updated value
    

Alternative: Memory-efficient iteration (for large bytearrays)

If you're working with large bytearrays and want to avoid creating an intermediate bytes object, use itertools.chain.from_iterable() to stream the bytes directly into your buffer:

import itertools

class message():
    # ... (same header definitions and _header_sequence)
    
    def createBuffer(self):
        self.byteArrays = bytearray()
        self.byteArrays.extend(itertools.chain.from_iterable(self._header_sequence))
        return self.byteArrays

This approach iterates through each byte of every header in sequence without building a full intermediate bytes object, which can save memory for large datasets.

Note on your original code

I fixed a small bug in your return statement—you had return byteArrays but it should be return self.byteArrays since byteArrays is an instance attribute.

内容的提问来源于stack exchange,提问作者user4292309

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:08:29