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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With