Python 图实现 - __Contains__ + addEdge

Python Graph Implementation - __Contains__ + addEdge

你好,目前正在研究使用邻接列表格式将图实现到 python 中的教程。我遇到了一个示例,其中在 'class graph' 中使用了一个缩进的 contains 函数。如下图

def __contains__(self, n):
    return n in self.vertDict

vertDict是通过class初始化的字典。我可以请求解释此功能的用途吗?

def addEdge(self,h,t):         
    if h not in self.vertDict:
        newV = self.addVert(h)
    if t not in self.vertDict:
        newV = self.addVert(t)
    self.vertDict[h].addnewLink(self.vertDict[t])

两鸟一石,'addEdge' 函数我有点理解,但是参数 h 和 t 是什么?它在创建边缘吗?

欣赏!我一直在为这些实现而苦苦挣扎:'(

Could i request an explanation of what this functions purpose is?

def __contains__(self, n):
    return n in self.vertDict

__contains__ 定义 class 的实例在 innot in 运算符的右侧时的行为方式——例如,x in foox not in foo。 [1]

考虑以下示例:

class Foo(object):
    def __init__(self, bar):
        self.bar = bar
    def __contains__(self, x):
        return self.bar == x

f = Foo(3)
print 2 in f # => False
print 3 in f # => True

Two birds one stone, I sort of understand the 'addEdge' function but what are the arguments h and t? Is it creating edges?

ht 似乎都是顶点。此方法似乎在 ht 之间添加一条边,因此它看起来像 (h)-(t).

# from the name, the method looks like it might be creating edges,
# but let's investigate further!
def addEdge(self,h,t):     

    # the first "give-away" is it's checking if
    # `h` is in `self.vertDict`
    if h not in self.vertDict:
        # if it *isn't* in `self.vertDict`, it adds it
        newV = self.addVert(h)

    # it does a similar check for `t`
    if t not in self.vertDict:
        newV = self.addVert(t)

    # it then adds a link, or edge between `h` and `t` here
    self.vertDict[h].addnewLink(self.vertDict[t])

来源:

[1] What does __contains__ do, what can call __contains__ function