<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def serialize(self):
 """Encode a packet and store the resulted bytearray in self.data. This method is legal only when encoding a packet. """


        self.data = bytearray()
        r = self.protocols[::-1]
        for i, p in enumerate(r):
            if isinstance(p, packet_base.PacketBase):
                if i == len(r) - 1:
                    prev = None
                else:
                    prev = r[i + 1]
                data = p.serialize(self.data, prev)
            else:
                data = six.binary_type(p)
            self.data = bytearray(data + self.data)