How to change which class variable is being called depending on user input?
<p>I've created a class called <code>Earthquake</code> 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:</p>

<pre><code>earthquake1 = Earthquake()

answer = input("What data would you like to see?")
print(earthquake1.answer)
</code></pre>

<p>In the example above, if the user answers <code>magnitude</code>, I want to print out the class variable <code>earthquake1.magnitude</code>.</p>

<p>Is there some way of doing this?</p>

<p>You could use <code>getattr</code> which is equivalent to <code>earthquake.attr_name</code>. The difference is that <code>getattr</code> allows you to use a variable to access the name and supply a default value if that is not found.</p>

<p>In short:</p>

<pre><code> print(getattr(earthquake1, answer))
</code></pre>

<p>Or, if you need to use a default value instead of raising a <code>KeyError</code>:</p>

<pre><code>print(getattr(earthquake1, answer, "Instance variable {} not found".format(answer)))
</code></pre>

python class python-3.x class-variables