Is there a way to instantiate objects from a dictionary in python with input parameters?

Say I have some class:

class Object1:
   def __init__(self, input=None):

class Object2:
   def __init__(self, input=None):

I can probably define a dict like this:

objDict = {"a" : Object1(), "b" : Object2()}

This would instantiate objects with input of None. Is there a way I could use the dictionary as a template though so I could pass in a parameter? Like this:

firstObj = objDict["a"]("foo")

And if this is possible, would this be the best way of doing it?

1 answer

  • answered 2018-01-13 17:43 Ned Batchelder

    You are instantiating the class when you make the dictionary, which isn't what you want. Just put the classes as values:

    class_dict = {"a": Object1, "b": Object2}
    first_obj = class_dict["a"]("foo")