0

I have a list of string as follows:

list = ['ContactHandler', 'LogHandler', 'FileHandler', 'SystemHandler', 'WelcomeHandler'] 

I want to use this list to create 5 classes in a for loop. An example of one class is shown below.

class WelcomeHandler(BaseHandler):
        def get(self):
            response = HTTPResponse()
            response.write('WelcomeHandler')
            return response
1

2 Answers 2

1

You should use a dictionary for your classes and define them like this:

classes = {}
for name in classlist:
    class Handler(BaseHandler):
        def get(self):
            response = HTTPResponse()
            response.write(self.__class__.__name__)
            return response
    Handler.__name__ = name
    classes[name] = Handler
Sign up to request clarification or add additional context in comments.

2 Comments

Can I import these classes from another.py with the given names from the dictionary?
Not exactly. You can use import myfile; WelcomeHandler = myfile.classes['WelcomeHandler'], though. (That's assuming that this file is called myfile.py.
1

Make a dictionary mapping the name to the class:

classLookup = {
    'ContactHandler': ContactHandler, 
    'LogHandler'    : LogHandler,
    #...
}

Then you can instantiate the right class based on the string

className = input('what class to instantiate?')
handler = classLookup[className]()

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.