Python中能否将类内多个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 singlebytesobject in one go. Passing this toextend()fills your buffer in a single operation.- Crucially,
msg_hdr_THREEand 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

