How do i instantiate a class_name passed via cmd line

Peter Otten __peter__ at web.de
Sun Feb 14 08:48:16 EST 2016


Gregory Ewing wrote:

> 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)

If the convention is that strict you could also expose the class under an 
alias:

# in ebay.py
Site = Ebay

# in the client module
module = importlib.import_module(module_name)
instance = module.Site(product) 




More information about the Python-list mailing list