L
L
Larisa .•º2017-02-17 14:01:16
Django
Larisa .•º, 2017-02-17 14:01:16

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

2 answer(s)
P
Peter, 2017-02-17
@petermzg

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()

S
Stepan Krapivin, 2017-02-17
@xevin

create a dictionary, with classes and names

classes = {
  'Class1': Class1,
  'Class2': Class2
}

and call from this dictionary by name
eval(dict['name']).some_method()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question