2

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()

Subhu
  • 23
  • 2
  • Hi and welcome to SO, please provide a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). And have a look at [How do I ask a good question](https://stackoverflow.com/help/how-to-ask). Editing your question with these requirements will help you immensely to get a fast and proper answer. – LeoE Mar 09 '20 at 12:03

1 Answers1

2

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.")
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53