如何使用全局值打印 class 中的属性?

How can I use global values to print an attribute from a class?

我刚刚开始学习如何编码,所以如果您在这里发现任何错误,请警告我。

我有一个 class:

class Wii:

    def __init__(self, color, gamecube_comp, miinum, installed_games):
        self.color = color
        self.gamecube_comp = gamecube_comp
        self.miinum = miinum
        self.installed_games = installed_games

而且我希望能够根据外部字典和一些输入从 class 打印属性,所以我尝试了这个:

selections = {
"1": Wii_1,
"2": Wii_2,
"color": color,
"gamecube_comp": gamecube_comp,
"miinum": miinum,
"installed_games": installed_games
}

selected_wii = input("Select a Wii from the list (just the number)\n")
selected_att = input("State what you want to know about the selected Wii\n")

print(selections[selected_wii].selections[selected_att])

但是它不允许我打印,因为 selections 没有在 class 中定义。有没有办法让它能够读取 selections[selected_att] 即使它不在 class 内?

如果属性名称为文本(字符串),从现有实例中检索它的推荐方法是使用 getattr built-in:

print(getattr(selections[selected_wii], selected_att))

选择 Python 语言,源代码中的属性名称 hard-coded 与键名不同,其中键是任意数据以检索对应的映射值。这与 Javascript 形成对比,例如,两者可以互换。 但是,与在运行时将其名称作为数据检索源代码中命名的属性或字段不可能或非常困难的静态类型语言相比,Python 提供了易于使用的内省功能,允许那个,喜欢。 getattr 打电话。因此,当您的设计需要这种用法时,您可以随意使用。