Veek. M wrote:
I'm writing a price parser. I need to do the equivalent of perl's
$$var to instantiate a class where $car is the class_name.

I'm passing 'Ebay' or 'Newegg' or 'Amazon' via cmd-line. I have a module named ebay.py and a class called Ebay (price parser). I do something like:

\> main.py ebay motherboard

and this does: module = __import__(module_name)
but now i need to instantiate the class - right now I do:
 instance = module.Ebay(module_name, product)

how do i replace the 'Ebay' bit with a variable so that I can load any class via cmd line.

class Load(object):
    def __init__(self, module_name, product):
        try:
            module = __import__(module_name)
            instance = module.Ebay(module_name, product)
        except ImportError:
            print("Can't find module %s" % module_name)


Something like this should do it:

  instance = getattr(module, class_name)(module_name, product)

If the class name is always the same as the module name with the
first letter capitalized, you could use

  instance = getattr(module, module_name.capitalize())(module_name, product)

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to