(Using python) I am looking to generate a bytes (or can be string that I convert to bytes) that is a message to send over TCP. The format is (Header)(Length)(Payload)
.
Within (Header)
is a (PayloadType)
which determines the content of (Payload)
.
Equally, I am looking to take a response message of a similar format that I can parse into a class/object for later use. Again, the content of the response would determine what ‘properties’ the class object would have.
My first thought was something like:
class message():
def __init__(self, payloadType, data, propA=None, propB=None):
self._payloadType = payloadType
self._data = data
self._header = '123456'
self._propA = propA
self._propB = propB
def createPacket(self):
if self._payloadType == 1:
return self._header + self._payloadType + self._propA + self._data
elif self._payloadType == 2:
return self._header + self._payloadType + self._propB + self._data
# etc
def parsePacket(self, packet)
payloadType = packet(4:6)
if payloadType == 1:
self._propA = packet(10:12)
# etc
The issues I see with this is there a number of payloadType
and each has some commonality in the header but could have a number of different properties.
This would lead to lots of optional arguments being passed, lots of properties in the class that are potentially unused…all making the code hard to read I feel.
I feel that there is a better pattern for this in Python but I can’t figure out what it is – I’ve read about inheritance, mixins, dataclasses, @class_method, etc but not sure if any of those fit the bill.
Is there a standard pattern way of doing this?