Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can use variable class name and function in Python

Tags:

python

django

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()
like image 964
user3214546 Avatar asked May 13 '26 07:05

user3214546


1 Answers

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.

like image 116
Patrick Maupin Avatar answered May 14 '26 22:05

Patrick Maupin



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!