I've created a class called Earthquake
which stores relevant earthquake data (its magnitude, time it hit, etc.) in class variables. I want to ask the user which data they'd like to see, then print out that data for them like so:
earthquake1 = Earthquake()
answer = input("What data would you like to see?")
print(earthquake1.answer)
In the example above, if the user answers magnitude
, I want to print out the class variable earthquake1.magnitude
.
Is there some way of doing this?
Just use getattr
:
earthquake1 = Earthquake()
answer = input("What data would you like to see?")
print(getattr(earthquake1, answer))