Creating Set of objects of user defined class in python

前端 未结 1 1959
我在风中等你
我在风中等你 2020-12-03 07:45
table = set([])

class GlobeLearningTable(object):
    def __init__(self,mac,port,dpid):

        self.mac = mac
        self.port = port
        self.dpid = dpid

          


        
1条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 08:13

    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
    

    0 讨论(0)
提交回复
热议问题