如何根据用户输入更改正在调用的 class 变量?

How to change which class variable is being called depending on user input?

我创建了一个名为 Earthquake 的 class,它在 class 变量中存储相关地震数据(震级、发生时间等)。我想询问用户他们想要查看哪些数据,然后像这样为他们打印出该数据:

earthquake1 = Earthquake()

answer = input("What data would you like to see?")
print(earthquake1.answer)

在上面的例子中,如果用户回答magnitude,我想打印出class变量earthquake1.magnitude

有什么方法可以做到这一点吗?

您可以使用 getattr,它等同于 earthquake.attr_name。不同之处在于 getattr 允许您使用变量来访问名称并在未找到时提供默认值。

简而言之:

 print(getattr(earthquake1, answer))

或者,如果您需要使用默认值而不是引发 KeyError

print(getattr(earthquake1, answer, "Instance variable {} not found".format(answer)))

只需使用getattr:

earthquake1 = Earthquake()

answer = input("What data would you like to see?")
print(getattr(earthquake1, answer))