[英]Python:How to print object key in a dictionary properly?
假設我有一個Graph類和一個Vertex類,定義如下
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
如果我這樣做:
G = Graph()
G.addVetex(1,None)
G.addVetex(2,None)
G.addVetex(1,3)
print G
它打印出{<Vertex.Vertex instance at 0x110295b90>: [], <Vertex.Vertex instance at 0x110295bd8>: []}
但是我期待類似{"Key:1 Value:None":[]...}
我的問題是我做錯了什么? 當一個詞被打印出來時,為什么它不會嘗試調用其鍵/值的str函數?
謝謝。
我相信你想用你當前代碼獲得你想要的字符串的方法是Vertex.__repr__
,這是python字典用來獲取鍵的字符串表示的方法。
這是一個相關的stackoverflow答案,它揭示了__repr__
和__str__
之間的區別。
Joe的回答是正確的,這是代碼的測試版本:
def __repr__(self):
return "Key: "+str(self.key)+" Value: "+str(self.value)
在Vertex
實現。 同樣重要的是返回一個字符串,而不是問題中的元組。
這樣做。 注意添加repr方法(以及str方法的一點清理)。
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)
但是,您可以考慮為您的頂點類繼承dict。 您可以獲得dict的所有好處,但可以添加方法以滿足您的需求。 最簡單的版本如下:
class Vertex(dict):
pass
你可以做像:
class Graph(object):
def __str__(self):
return ", ".join("Key: " + str(i.key) + " Value: " + str(i.value) for i in self.adjacencyList)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.