+ 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.

25th Feb 2018, 9:36 PM
kaduribeiro
kaduribeiro - avatar
3 odpowiedzi
+ 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)' )
26th Feb 2018, 3:10 PM
Rugved Modak
Rugved Modak - avatar
+ 2
You can't use a variable to define a class name. That is what you are tying to do right?
26th Feb 2018, 11:51 AM
Rugved Modak
Rugved Modak - avatar
+ 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)
26th Feb 2018, 1:09 PM
kaduribeiro
kaduribeiro - avatar