集中的对象成员资格

时间:2012-03-22 23:51:19

标签: python class operators membership

这实际上是两个问题:

  1. 为什么不会调用成员运算符(__contains__)?

  2. 为什么D在nodeList中,但不在nodeSet中?

  3. 我的目标是让D与nodeList和nodeSet“同时”,因为它与A具有相同的loc。

    class Node(object):
        def __init__(self, loc):
            self.loc = loc
    
        def __eq__(self, other):
            print "eq: self.getLoc(): {}, other.getLoc(): {}".format(self.getLoc(),     other.getLoc())
            if self.getLoc() == other.getLoc():
                return True
            return False
    
        def __contains__(self, other):
            print "contains: self.getLoc(): {}, other.getLoc(): {}".format(self.getLoc(),  other.getLoc())
            if self.getLoc() == other.getLoc():
    
                return True
            return False
    
        def setLoc(self, loc):
            self.loc = loc
    
        def getLoc(self):
            return self.loc
    
    
    if __name__ == "__main__":
        A = Node((1,1))
        B = Node((2,2))
        C = Node((3,3))
    
        D = Node((1,1))
    
        nodeList = [A, B, C]
        nodeSet = set()
        nodeSet.add(A)
        nodeSet.add(B)
        nodeSet.add(C)
    
        print "A in nodeList: {}".format(A in nodeList)
        print "A in nodeSet: {}".format(A in nodeSet)
        print "D in nodeList: {}".format(D in nodeList)
        print "D in nodeSet: {}".format(D in nodeSet)
    

    返回True,True,True,False。显然,从不调用__contains__运算符。我希望它能回归真,真,真,真。

    对我的代码的任何其他批评当然都是受欢迎的,因为我是初学者。

2 个答案:

答案 0 :(得分:3)

为什么Node.__contains__会被调用?您永远不会有Node作为in表达式的右侧。

答案 1 :(得分:-1)

the documentation re __hash__() - 简而言之:

  

[I] f [a class]定义__cmp__()__eq__()但不定义__hash__(),   它的实例不能用于散列集合。

set是一个哈希集合。您需要确保实施Node.__hash__()