避免为多个类重写常用函数

时间:2017-04-02 17:51:01

标签: python python-3.x

我遇到以下情况:我有一个课程Application,它在页眉和页脚中包含data,并添加checksum来制作packetTCP继承自Application,并与从packet获得的Application执行完全相同的过程(即,它将super调用到make_packet,然后使它成为自己的。)

由于make_packet代码对于这两个类都是相同的,除了页眉和页脚值之外,我试图使用闭包,如下所示。 下面的重要一行是self.packet = cls_name.header + self.packet + cls_name.footer中的cmake_packet

def make_make_packet(cls_name):
    def cmake_packet(self):
       self.packet = cls_name.header + self.packet + cls_name.footer
       checksum = self.packet[::-1]
       self.packet += checksum
       return self.packet

    return cmake_packet()


class Application:
    header = footer = "001101"

    def __init__(self, data):
        self.packet = data

    make_packet = make_make_packet(Application)


class TCP(Application):
    header = footer = "110011"

    def __init__(self, data):
        super().__init__(data)
        self.packet = super().make_packet()

    make_packet = make_make_packet(TCP)

并通过网络发送数据包,我只需致电:

# data is something like "010"
tlayer = TCP(data)
# or send()
print(tlayer.make_packet())

问题是上面的定义会出错,因为调用make_make_packet(Application)时,尚未定义Application

有没有办法解决这个问题而不重复几个类的功能,并且不使用self.header (这在此无效)

注意: make_packet()需要为每个TCP数据包调用两次,而不是一次(OSI七层模型)。首先Application将原始数据包装在一个数据包中,然后通过TCP进一步将其包含在更大的数据包中,方法是添加它自己的标题。

1 个答案:

答案 0 :(得分:0)

self.也可以访问类属性。

class Application:
    header = footer = "001101"

    def __init__(self, data):
        self.packet = data

    def make_packet(self):
       self.packet = self.header + self.packet + self.footer
       checksum = self.packet[::-1]
       self.packet += checksum
       return self.packet


class TCP(Application):
    header = footer = "110011"

    def __init__(self, data):
        data = Application(data).make_packet()
        super().__init__(data)