2017-04-02 14 views
0

我有以下情况:我有一个类Application,它在页眉和页脚中包含data,并添加checksum以创建packetTCP继承自Application并且执行与从Application获得的packet完全相同的过程(即,它调用supermake_packet然后使其自己)。避免重写多个类别的通用功能

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

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七层模型)。 First Application将原始数据封装在数据包中,然后通过添加它自己的头文件将数据包进一步封装在更大的数据包中,格式为TCP

+0

我不明白你为什么不能为'packet'方法使用继承。 –

+0

@DanielRoseman我没有得到你,请你详细说明一下吗? 'packet'不是一个方法,它是一个实例变量。 – forumulator

回答

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) 
+0

只需在'TCP.__ init__'中使用'self.make_packet()'。 –