![](/img/trans.png)
[英]Dictionary and Input: if the `input` contains any of the keys I want to print the value
[英]I want to print keys in a dictionary from class
我正在嘗試打印存儲在字典中作為鍵的行星名稱,但是我什么也沒得到,只有空格
這是我的代碼:
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)
您實際上需要打印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)
您最后需要添加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
__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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.