String representation of an object in Python

So in the book ( Solving Problems with Algorithms and Data Structures ) that I am currently using as a reference, this is what the graph looks like. Here I do not understand how the function works __str__

in the class Vertex

and why we need it. Can someone please explain? Thank!

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

      

+3


source to share


2 answers


One line of code would be enough to ask your question:

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

      

Throw it away separately:

  • self.id

    - the unique identifier of your object. str()

    converts it to string.
  • we concatenate connectedTo:

    and then
  • str()

    transformation of the list generated by the construction [...]

    .


I think 3. is giving you problems. This is just a central Pythonic construct and selects each element of the sequence self.connectedTo

, takes .id

and returns a list of them.

After that, you have a string that returns __str__

. Since this method is called whenever python tries to get the lowercase form of an object, it can be called when you do something like

print Vertex

      

+3


source


A function __str__

is what is called when trying to harden an object, so

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

      



this can be implemented to make it easier to print objects

+2


source







All Articles