Python - Class Factory

285 views Asked by At

I'm using classes to design network conversations, I have this code:

class Conversation(object):
    __metaclass__ = ABCMeta

    def __init__(self, received=0, sent=0):
        self.sent = sent
        self.received = received

    def __str__(self):
        return "<Conversation: received=" + str(self.received) + " sent=" + str(self.sent) + " >"

    def __eq__(self, other):
        return isinstance(other, Conversation)

    @classmethod
    def filter(cls, pkt):
        return True

    @abstractmethod
    def is_sent(self, pkt):
        raise NotImplementedError

    def add(self, pkt):
        if self.is_sent(pkt):
            self.sent += 1
        else:
            self.received += 1

class IPConversation(Conversation):
    def __init__(self, a_ip, b_ip, received=0, sent=0):
        super(IPConversation, self).__init__(received, sent)
        self.a_ip = a_ip
        self.b_ip = b_ip

    def __str__(self):
        return "<IPConversation: " + self.a_ip + " >>> " + self.b_ip

    def __eq__(self, other):
        if super(IPConversation, self).__eq__(other):
            a = (self.a_ip, self.b_ip)
            b = (other.ip_a, other.ip_b)
            return a == b or a == b[::-1]
        return False

    @classmethod
    def filter(cls, pkt):
        return super(IPConversation, cls).filter(pkt) and 'IP' in pkt
    def is_sent(self, pkt):
        return self.a_ip == pkt['IP'].src

but then I thought about creating the IPv6 class, and it will be the same as the IP class but the only difference is the 'IPv6' in pkt in front of 'IP' in the classmethod. how can I do it with a metaclass?

0

There are 0 answers