1

Hey there so currently working on a tutorial on implementing graphs into python using an adjacency list format. I came across an example whereby in the 'class graph' there was an indented contains function used. As shown below.

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

vertDict is a dictionary initialised through the class. Could i request an explanation of what this functions purpose is?

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])

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

Appreciate it! I have been seriously struggling with these implementations :'(

1 Answers1

3

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

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

__contains__ defines how instances of a class behave when they're on the right side of an in or not in operator -- e.g., x in foo or x not in foo. [1]

Consider the following example:

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?

Both h and t appear to be vertices. This method appears to be adding an edge between h and t so it will look like (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])

Sources:

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

Community
  • 1
  • 1
Michael Recachinas
  • 2,739
  • 2
  • 20
  • 29
  • Thank you for clearing this up. I'm still a little ensure of what 'behaviour' changes may happen to instances? Does it make instances exclusive? –  Dec 09 '15 at 21:55
  • No, without `__contains__`, if you try `print x in f`, it will throw a `TypeError`. `__contains__` changes the class so that you can say `x in f` for all instances of the class (in our case, `Foo`). – Michael Recachinas Dec 09 '15 at 21:58
  • Oh yes, understood! So it acts as a mutual means of instance translation. Makes sense to me, thanks very much! –  Dec 09 '15 at 22:01