How do i instantiate a class_name passed via cmd line
Veek. M
vek.m1234 at gmail.com
Sun Feb 14 00:51:08 EST 2016
Gregory Ewing wrote:
> 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)
>
Ah! i see - clever!
'getattr' returns the class object with class_name=whatever
and we can instantiate now that we have a class object - nice - thanks
guys - the bell should have rung from Rick's example.
More information about the Python-list
mailing list