Call a particular python class using User input

Viewed 122

I'm a newbee to python, hope you don't mind if this is a wrong question. I have different category classes which has methods and return statement in it. I need to call a particular class respective of the user input. For Example, If user inputs a particular category like 'travel', I need to call the class named 'travel'. I have written a simple code, where am saving the user input in a variable called category and values . am trying to call the class under the file calculate.py.

category = args.category values = args.values obj = calculate.category(values) obj.calc()

1 Answers

The safest way is to have a dictionary somewhere that specifies the correspondence between pre-selected user responses, and the relevant classes. For example, if you have the classes InternationalTravel, DomesticTravel, and OverseasTravel, maybe you do something like this:

correspondence = {
  'international': InternationalTravel,
  'domestic': DomesticTravel,
  'overseas': OverseasTravel,
}

travel_type = input("What type of travel? ")
try:
  travel = correspondence[travel_type]()  # get the class, then initialize a new instance
except KeyError:
  print("That's not a possible type of travel.")
Related