Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use class from file based of name in string form (Python)

Currently, I am importing every class I have in a python file in my main "Runner" script. The goal is to, based on a string given, instantiate the class that has the same name as the string given.

For example:

If there is a class called 'Test':

class Test():

if the String is "Test", it will call that class.

like image 223
Ron Arel Avatar asked Dec 07 '25 14:12

Ron Arel


1 Answers

It's seems a reflection case, that are explained here.

Example from ref:

module = __import__(module_name)
class_ = getattr(module, class_name)
instance = class_()
like image 97
bcosta12 Avatar answered Dec 09 '25 03:12

bcosta12



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!