user1610719
user1610719

Reputation: 1303

Taking user input to load a class

This should be simple but I can't find the right Google phrase to find it. Just looking for the code needed in def loadClass(), not sure what it would be. Thanks in advance!

class ClassA():
    def __init__(self,date):
        pass
class ClassB():
    def __init__(self,date):
        pass
def loadClass(className,date):
    loadedClass = className(date)

loadClass(ClassA,'1/1/2013')
loadClass(ClassB,'1/2/2013'

Upvotes: 0

Views: 57

Answers (1)

Jon Clements
Jon Clements

Reputation: 142156

If you're literally taking a string as the class name, then you could generate a lookup of "class name" to "class object" mapping, and use that:

allowed_classes = {
    'A': ClassA,
    'B': ClassB
}

def load_class(class_name, *args, **kwdargs):
    return allowed_classes[class_name](*args, **kwdargs)

new_class_obj = load_class('B', 'Jan 1st')

Upvotes: 2

Related Questions