I have this class
class Test(object):
def __init__(self, *args, **kwargs)
pass
def make(self):
pass
Now i have class name and function name as variables like
class_name = "Test"
func_name = "make"
i want to call Test(**kwargs).make()
I tried this
cls_name = "Test"
callback = getattr(cls_name, "make")
obj = callback()
Assuming your class is at global level, you can access it through globals(). (Other possible options are locals() or vars().) For example:
>>> class Test(object):
... def __init__(self, *args, **kwargs):
... print("in test init")
... def make(self):
... print("in test make")
...
>>> cls_name = "Test"
>>> method_name = "make"
>>> callback = getattr(globals()[cls_name](), method_name)
in test init
>>> callback()
in test make
If your Test class were in a different module, you could use getattr(module_containing_test, cls_name) instead of the globals() lookup.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With