table = set([])
class GlobeLearningTable(object):
def __init__(self,mac,port,dpid):
self.mac = mac
self.port = port
self.dpid = dpid
def add(self):
global table
if self not in table:
table.add(self)
class LearningSwitch(object):
def __init__ (self, connection, transparent):
self.connection = connection
self.transparent = transparent
self.macToPort = {}
connection.addListeners(self)
self.hold_down_expired = _flood_delay == 0
def _handle_PacketIn (self, event):
packet = event.parsed
self.macToPort[packet.src] = event.port # 1
packet_src = str(packet.src)
packet_mac = packet_src.upper()
entry = GlobeLearningTable(packet_mac, event.port, dpid_to_str(self.connection.dpid))
entry.add()
问题:entry.add()
方法每次调用都会添加新对象并增加表中的项目。
这不应该发生,因为
- 在添加方法中,我检查该对象是否在表中,然后添加该特定对象。
- 表是一个集合,是一个无序列表,不应该有重复的对象。
求助:在这个设置中有什么方法可以只在对象不在表中时添加对象。
最佳答案
您需要实现 __eq__
和 __hash__
教 Python 如何识别独特的 GlobeLearningTable
实例的方法。
class GlobeLearningTable(object):
def __init__(self,mac,port,dpid):
self.mac = mac
self.port = port
self.dpid = dpid
def __hash__(self):
return hash((self.mac, self.port, self.dpid))
def __eq__(self, other):
if not isinstance(other, type(self)): return NotImplemented
return self.mac == other.mac and self.port == other.port and self.dpid == other.dpid
现在你的对象是可比较的,相等的对象也会为 __hash__
返回相等的值。这让 set
和 dict
对象有效地存储您的对象并检测它是否已经存在:
>>> demo = set([GlobeLearningTable('a', 10, 'b')])
>>> GlobeLearningTable('a', 10, 'b') in demo
True
关于python - 在python中创建用户定义类的对象集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17493307/