我正在使用类来设计网络对话,我有这段代码:
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
然后我考虑创建IPv6类,它将与IP类相同,但唯一的区别是 classmethod 中“IP”前面的pkt中的“IPv6” 。我怎么能用元类来做呢?