Answer the question
In order to leave comments, you need to log in
Convert string to class name?
There is a dictionary with a string class name. dic = {'name':'Class1'}
]
And there is the class itself Class1= class...
, is it possible to get the value from the dictionary, which is returned in the string format, convert it into a class, to call methods?
Answer the question
In order to leave comments, you need to log in
You need to know not only the class name, but also the module name.
If everything is in one file, then the example will be like this:
import sys
class TestClass:
def __init__(self):
self.name = 'TestClass - 2'
def write(self):
print self.name
module = sys.modules[__name__]
class_ = getattr(module, 'TestClass')
instance = class_()
instance.write()
create a dictionary, with classes and names
classes = {
'Class1': Class1,
'Class2': Class2
}
eval(dict['name']).some_method()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question