Created
November 24, 2015 18:35
-
-
Save sobolevnrm/dd72550b571339e16997 to your computer and use it in GitHub Desktop.
I am trying to create the object of a class when I have only the string of the class name avoiding a bunch of conditionals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# I have lots of classes with very similar constructors. I'd like to avoid a huge if elseif ... statement | |
# This works when all classes are specified in the global scope but breaks across modules -- it also doesn't seem very safe | |
class Foo: | |
def __init__(self): | |
self.bar = "FOOBAR" | |
class_name = "Foo" | |
ctor = globals()[class_name] | |
obj = ctor() | |
print(obj.bar) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a solution that fits your example, where the class is defined in the same file in which it's used:
This SO answer will prove helpful should you want to know more about how this works, or decide that you want to access your class from a different file/module.