2015-04-03 44 views
0

我想打印行星被存儲在字典中的鍵名字典中的打印按鍵,但是我得到什麼都沒有,只是空間我想從

這是我的代碼:

class planets: 
    def __init__(self, aDict): 
     self.aDict = aDict 
    def __str__(self): 
     for key in self.aDict.keys(): 
      print(key) 



aDict = {"Sun": 1000, "Mercury": 10, "Earth": 60, "Mars": 50, "jupiter": 100} 
p = planets(aDict) 

回答

5

你需要實際打印p和__str__需要返回一個字符串,如:

def __str__(self): 
     return ' '.join(sorted(self.aDict, key=self.aDict.get)) 

aDict = {"Sun": 1000, "Mercury": 10, "Earth": 60, "Mars": 50, "jupiter": 100} 
p = planets(aDict) 
print(p) 
+0

爲什麼按隨機順序打印它們?有沒有辦法讓它按價值順序打印? – Mozein 2015-04-03 03:45:40

+1

口令沒有排序...但你可以調整代碼來訂購它們...... – AChampion 2015-04-03 03:46:54

+2

你也可以使用'return'\ n'.join(sorted(self.aDict,key = self.aDict.get))' 。 – TigerhawkT3 2015-04-03 03:50:21

0

您需要在最後添加p.__str__()

class planets: 
    def __init__(self, aDict): 
     self.aDict = aDict 
    def __str__(self): 
     for key in self.aDict: 
      print(key) 



aDict = {"Sun": 1000, "Mercury": 10, "Earth": 60, "Mars": 50, "jupiter": 100} 
p = planets(aDict) 
p.__str__() 

輸出:

Mercury 
Sun 
Mars 
jupiter 
Earth 
+0

'在self.aDict鍵:'會更合適 – 2015-04-03 03:43:21

+0

是的,正確的... – 2015-04-03 03:44:51

+1

_ \ _ str__由蟒紋功能使用時,直接調用它,而不是尊重的標準定義_ \ _ str__可能不是一個好主意 – AChampion 2015-04-03 03:46:04

0

__str__ 「魔術方法」 應該return一而不是自己做任何打印。有這樣的方法,不會return一個字符串生成一個錯誤。使用該方法建立一個字符串,然後返回該字符串。然後,您可以使用print(p)「神奇地」調用該方法。例如:

>>> aDict = {"Sun": 1000, "Mercury": 10, "Earth": 60, "Mars": 50, "jupiter": 100} 
>>> class planets(object): 
...  def __init__(self, aDict): 
...   self.aDict = aDict 
...  def __str__(self): 
...   return '\n'.join(self.aDict) 
... 
>>> print(planets(aDict)) 
Mercury 
Sun 
Earth 
Mars 
jupiter