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()
Problem : entry.add()
method adds new object every time it is called and increments the items in the table.
This should not happen because
Help: is there any way in this set up I can add the object only when it's not in the table.
User-defined method objects may be created when getting an attribute of a class (perhaps via an instance of that class), if that attribute is a user-defined function object, an unbound user-defined method object, or a class method object.
Creating Python Sets A set is created by placing all the items (elements) inside curly braces {} , separated by comma, or by using the built-in set() function. It can have any number of items and they may be of different types (integer, float, tuple, string etc.).
The set is a Python implementation of the set in Mathematics. A set object has suitable methods to perform mathematical set operations like union, intersection, difference, etc. A set object contains one or more items, not necessarily of the same type, which are separated by a comma and enclosed in curly brackets {}.
You need to implement __eq__
and __hash__
methods to teach Python about how to recognise unique GlobeLearningTable
instances.
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
Now your object is comparable, and equal objects will also return equal values for __hash__
. This lets set
and dict
objects store your objects efficiently and detect if it is already present:
>>> demo = set([GlobeLearningTable('a', 10, 'b')]) >>> GlobeLearningTable('a', 10, 'b') in demo True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With