Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate a Python class from a name [duplicate]

Tags:

So i have a set of classes and a string with one of the class names. How do I instantiate a class based on that string?

class foo:   def __init__(self, left, right):      self.left = left      self.right = right  str = "foo" x = Init(str, A, B) 

I want x to be an instantiation of class foo.

like image 248
klynch Avatar asked Feb 09 '10 02:02

klynch


1 Answers

In your case you can use something like:

get_class = lambda x: globals()[x] c = get_class("foo") 

And it's even easier to get the class from the module:

import somemodule getattr(somemodule, "SomeClass") 
like image 77
Radagast Avatar answered Nov 03 '22 01:11

Radagast