Dynamic class creation - Python
<p>Here is the scenario:</p>

<p>I have two classes:</p>

<pre><code>class A:
  pass:

class B:
  pass
</code></pre>

<p>Now I want to create a client, in that I need to have a small utility method, which should return my class template/object e.g: class A, class B, as I pass on the class name to that utility e.g <code>get_obj(classA)</code>.</p>

<p>Now, is this possible? If then please suggest an approach, as I don't get any correct answer as of now in web.</p>

<p>Hope I am making sense.</p>

<p>Here is a possible implementation. All the code is contained in a single '.py' file</p>

<pre><code>class A:                                                                                            
   pass                                                                                             


class B:                                                                                            
   pass                                                                                             

# map class name to class                                                                                                    
_classes = {                                                                                        
         A.__name__: A,                                                                             
         B.__name__: B,                                                                             
}                                                                                                   

def get_obj(cname):                                                                                       
    return _classes[cname]()                                                                            

# test the function                                                                                                    
if __name__ == '__main__':                                                                          
   print get_obj('A')   
</code></pre>

<p>It will produce the following output</p>

<pre><code>&lt;__main__.A instance at 0x1026ea950&gt;
</code></pre>

python oop inheritance