4

Let's say I have a class like this

class MyClass(AnotherClass):
  def __init__(self, arg1, arg2):
    self.arg1 = arg1
    self.arg2 = arg2

  def f(self):
    #dostuff

And I have the string "my class"

str = "my class"

I can do this:

class_name_from_str = str.title().replace(" ", "") # now class_name_from_str is "MyClass"

How could I make class_name_from_str callable? I want something like this:

callable_obj = some_process(class_name_from_str)
o = callable_obj(arg1, arg2)
o.f()

I'm using Python 2.7, by the way

UPDATE: As Matti Virkkunen suggested in a comment, a good solution is to create a dict to map strings with classes

my_calls_dict = {'my class' : MyClass, 'my other class' : MyOtherClass}
Community
  • 1
  • 1
Jorge Arévalo
  • 2,858
  • 5
  • 36
  • 44

1 Answers1

6

It kind of depends on where your class resides. If it's in the current module

globals()[class_name]

should get you the class. If it's in a module, replace globals() with the module (possibly imported via __import__() - if you want the module name to be dynamic as well).

This would be a good time to think about whether this is a good idea though. Wouldn't it be clearer to, for instance, make a dict of names and corresponding classes? If your .title().strip() thing is part of your actual code, I honestly can't think of what it might be trying to do.

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159