4

So in the book(Problem Solving with Algorithms and Data Structres) that I'm currently using as a reference, this is how a graph is implemented. What I don't understand here is how exactly the __str__ function in the class Vertexworks here and why we need it. Can anyone please explain? Thank you!

 class Vertex:
     def __init__(self,key):
         self.id = key
         self.connectedTo = {}

     def addNeighbor(self,nbr,weight=0):
         self.connectedTo[nbr] = weight

     def __str__(self):
         return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo])

     def getConnections(self):
         return self.connectedTo.keys()

     def getId(self):
         return self.id

     def getWeight(self,nbr):
         return self.connectedTo[nbr]




 class Graph:
     def __init__(self):
         self.vertList = {}
         self.numVertices = 0

     def addVertex(self,key):
         self.numVertices = self.numVertices + 1
         newVertex = Vertex(key)
         self.vertList[key] = newVertex
         return newVertex

     def getVertex(self,n):
         if n in self.vertList:
             return self.vertList[n]
         else:
             return None

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

     def addEdge(self,f,t,cost=0):
         if f not in self.vertList:
             nv = self.addVertex(f)
         if t not in self.vertList:
             nv = self.addVertex(t)
         self.vertList[f].addNeighbor(self.vertList[t], cost)

     def getVertices(self):
         return self.vertList.keys()

     def __iter__(self):
         return iter(self.vertList.values())
0

2 Answers 2

3

the __str__ function is what's called when you attempt to stringify the object, so

g = Vertex(key)
print str(g) # calls __str__

this can be implemented to make printing objects easier

Sign up to request clarification or add additional context in comments.

Comments

3

One line of code would have sufficed to ask your question:

str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo])

Let's pick that apart:

  1. self.id is the unique ID of your object. str() converts that to a string.
  2. we concatenate connectedTo: and then the
  3. str() conversion of a list as generated by the [...] construct.

I guess 3. is giving you problems. It's just a central Pythonic construct and selects every element in the self.connectedTo sequence, takes .id of that and returns a list of these.

After that, you have a string, that __str__ returns. Since that method is called whenever python tries to get a string form of an object, it might be called when you do something like

print Vertex

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.