+ 3
[python] How to pass a string and use it to define the name of a class to be instantiated?
I need to define the name of a class using a dictionary and pass it to a method. In this method I need to instantiate the class received in the format of string.
3 Respuestas
+ 4
create a string of it like 'xclass.yourmethod(params)' which is exactly what you want to evaluate and pass it to eval() function like eval( 'xclass.yourmethod(params)' )
+ 2
You can't use a variable to define a class name. That is what you are tying to do right?
+ 1
the class is already defined, but I need to invoke the class passing a string as a parameter. Something like this
def ClassA(self):
pass
def ClassB(self):
pass
def method(**class_dict):
for a_class in class_dict
# Here I need the code to instantiate or call a method for each class in the dictionary
#main
class_dict = {1:”ClassA”, 2:”ClassB”}
method(class_dict)