0

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?

5
  • if statements? docs.python.org/3/tutorial/controlflow.html Commented Aug 29, 2016 at 3:21
  • 1
    Probably getattr... also easily done with eval but eval is evil Commented Aug 29, 2016 at 3:22
  • @dfasoro I'd rather not use if statements because I've got over 20 attributes Commented Aug 29, 2016 at 3:29
  • 1
    Ok, @A.J. 's answer below should suffice, I will suggest you sanitize/filter the input in case you have some attributes (asides the 20) in the earthquake object you don't necessarily want the user to see. Commented Aug 29, 2016 at 3:32
  • How do Earthquake instances know about what earthquake they're about? Commented Aug 29, 2016 at 4:12

2 Answers 2

4

Just use getattr:

earthquake1 = Earthquake()

answer = input("What data would you like to see?")
print(getattr(earthquake1, answer))
Sign up to request clarification or add additional context in comments.

Comments

2

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

In short:

 print(getattr(earthquake1, answer))

Or, if you need to use a default value instead of raising a KeyError:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.