Nikhil
Nikhil

Reputation: 545

Instantiate class based on request parameter

I would like for the user to specify via input parameters which classes they would like to instantiate. I know how to get the parameter from the request, but how can I instantiate the specified class without using many if statements?

request['classToUse'] = Class1
newClass = request['classToUse']()

Upvotes: 0

Views: 389

Answers (2)

davidism
davidism

Reputation: 127190

Allow the user to specify a string representing one of the available classes. Look up the class by the string provided.

# map class names to classes
avail = dict((cls.__name__, cls) for cls in (Spam, Eggs, Toast))

@app.route('/hello')
def hello():
    name = request.args['name']
    obj = avail[name]()
    return 'you created a {}'.format(name)

Navigating to /hello?name=Toast will create an instance of the Toast class.

Upvotes: 1

Lawrence Benson
Lawrence Benson

Reputation: 1406

if request contains Class1 at classToUse, then your code should work. A basic example to show:

class A(object):
    def __init__(self):
        self.a = 5

d = {'a': A}
my_obj = d['a']()
print my_obj.a

returns

5

here you can see, that it is instantiated with ()

Upvotes: 0

Related Questions