2013-07-05 32 views
0
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()方法每次調用時都會添加新對象,並增加表中的項。在Python中創建用戶定義類的對象集

這是不應該發生,因爲

  1. 在添加方法,我檢查是在表對象或沒有,然後我補充說,特定的對象。
  2. 表是一個無序列表,它不應該有重複的對象。

幫助:有沒有什麼辦法可以在這個設置中添加對象,只有當它不在表格中。

+0

你可能是指'表=集()',而不是'集合([])' – ersran9

回答

9

您需要實施__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__返回相同的值。這讓setdict對象有效地存儲你的對象,並檢測它是否已經存在:

>>> demo = set([GlobeLearningTable('a', 10, 'b')]) 
>>> GlobeLearningTable('a', 10, 'b') in demo 
True 
+0

感謝您的Martijn Pieters的。現在它按照我想要的方式工作。除此之外,我還學到了Python的另一個基礎。 –

相關問題