How do i instantiate a class_name passed via cmd line

Cameron Simpson cs at zip.com.au
Sun Feb 14 00:20:06 EST 2016


On 14Feb2016 10:10, Veek. M <vek.m1234 at gmail.com> 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)

Ebay = geattr(module, 'Ebay')

or

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

Cheers,
Cameron Simpson <cs at zip.com.au>


More information about the Python-list mailing list