3

Say I have a Graph class and a Vertex class, defined as below

Graph.py

class Graph:

def __init__(self):
    self.adjacencyList = {}

def __str__(self):
    return str(self.adjacencyList)

def addVetex(self,key,value):
    if Vertex(key,value) not in self.adjacencyList:
        self.adjacencyList[Vertex(key,value)] = []

Vertex.py

class Vertex:
def __init__(self,key,value):
    self.key = key
    self.value = value

def __str__(self):
    return "Key: ",str(self.key)," Value: ",str(self,value)

def __hash__(self):
    return self.key

if I do this:

G = Graph()
G.addVetex(1,None)
G.addVetex(2,None)
G.addVetex(1,3)
print G

It print out {<Vertex.Vertex instance at 0x110295b90>: [], <Vertex.Vertex instance at 0x110295bd8>: []} But I am expecting something like {"Key:1 Value:None":[]...}

My question is what I am doing wrong? When a diction got print out, why it does not try to call the str function of its keys/values?

Thanks.

Bob Fang
  • 6,963
  • 10
  • 39
  • 72
  • You set a `Vertex` object as your key: `self.adjacencyList[Vertex(key,value)] = []`, hence the key is the object itself and not `1` or `2`, ... – Alex Jan 11 '13 at 12:10
  • Yeah I know that, is there any way I can print it out properly? – Bob Fang Jan 11 '13 at 12:13
  • Ah, now I understand what you mean. Well, I cannot answer that, but I think its a good question. – Alex Jan 11 '13 at 12:14

4 Answers4

5

I believe the method you want to implement to get the string you want with your current code is Vertex.__repr__, which is what the python dictionary uses to get string representations of keys.

Here's a related stackoverflow answer that sheds some light on the difference between __repr__ and __str__

Community
  • 1
  • 1
Joe Day
  • 6,965
  • 4
  • 25
  • 26
1

Joe's answer is correct, here is the tested version of the code:

def __repr__(self):
    return "Key: "+str(self.key)+" Value: "+str(self.value)

to be implemented in Vertex. Also important is that a string is given back, not a tuple as in the question.

Alex
  • 41,580
  • 88
  • 260
  • 469
1

This will do it. Note the addition of the repr method (and a little cleanup of the str method).

class Vertex:
    def __init__(self,key,value):
        self.key = key
        self.value = value

    def __str__(self):
        return "{Key: "+str(self.key)+" Value: "+str(self.value)+"}"

    def __hash__(self):
        return self.key

    def __repr__(self):
        return str(self)

You might consider subclassing a dict, though, for your vertex class. You get all the benefits of a dict but can add methods to suit your needs. The simplest version of this would look like:

class Vertex(dict):
    pass
seandavi
  • 2,818
  • 4
  • 25
  • 52
-1

You can do smth like:

class Graph(object):
    def __str__(self):
        return ", ".join("Key: " + str(i.key) + " Value: " + str(i.value) for i in self.adjacencyList)
alexvassel
  • 10,600
  • 2
  • 29
  • 31