Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: Cameron Simpson Newsgroups: comp.lang.python Subject: Re: How do i instantiate a class_name passed via cmd line Date: Sun, 14 Feb 2016 16:20:06 +1100 Lines: 35 Message-ID: References: Reply-To: python-list@python.org Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii; format=flowed X-Trace: news.uni-berlin.de fJ1xMZ7nbCPLrBLwKVEjhgJe4PYJ1NGJyw3Chk6X392g== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.005 X-Spam-Evidence: '*H*': 0.99; '*S*': 0.00; 'importerror:': 0.05; 'cc:addr:python-list': 0.09; 'subject:How': 0.09; 'cmd': 0.09; 'def': 0.13; 'from:addr:cs': 0.16; 'from:addr:zip.com.au': 0.16; 'from:name:cameron simpson': 0.16; 'instantiate': 0.16; 'message- id:@cskk.homeip.net': 0.16; 'motherboard': 0.16; 'parser.': 0.16; 'received:io': 0.16; 'received:psf.io': 0.16; 'simpson': 0.16; 'wrote:': 0.16; 'try:': 0.18; 'variable': 0.18; 'load': 0.20; 'cc:2**0': 0.20; 'cc:addr:python.org': 0.20; '%s"': 0.22; 'cheers,': 0.22; 'cc:no real name:2**0': 0.22; 'bit': 0.23; 'passing': 0.23; 'header:In-Reply-To:1': 0.24; 'module': 0.25; 'header:User-Agent:1': 0.26; 'skip:_ 20': 0.26; 'equivalent': 0.27; 'skip:_ 10': 0.32; 'class': 0.33; 'except': 0.34; 'instance': 0.35; 'replace': 0.35; 'something': 0.35; 'subject:: ': 0.37; 'charset:us-ascii': 0.37; 'received:localdomain': 0.38; 'where': 0.40; 'called': 0.40; 'cameron': 0.66; 'header:Reply- To:1': 0.67; 'price': 0.69; 'reply-to:no real name:2**0': 0.71; '>how': 0.84; 'ebay': 0.84; 'reply-to:addr:python.org': 0.84; 'subject:via': 0.84; 'do:': 0.91 Content-Disposition: inline In-Reply-To: User-Agent: Mutt/1.5.24 (2015-08-30) X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.21rc2 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Xref: csiph.com comp.lang.python:102907 On 14Feb2016 10:10, 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) Ebay = geattr(module, 'Ebay') or klass = getattr(module, module_name.capitalize()) instance = klass(module_name, product) Cheers, Cameron Simpson