我想从课堂上打印字典里的键

2024-04-25 09:54:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着打印行星的名字,这些名字作为一个键存储在字典里,但是我什么也得不到,只有空间

这是我的密码:

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)

Tags: keyinself密码for字典initdef
3条回答

您需要在最后添加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

您需要实际打印p,而uu str uuuuuuuuu需要返回一个字符串,例如:

    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)

__str__“magic method”应该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

相关问题 更多 >