Home > Mobile >  using globals() with class method in python
using globals() with class method in python

Time:06-07

class MyModules:
   def Play_Music(self):
     print(123)

function_name = 'Play_Music'

this is a simplified code. I need to call this function with a globals() function, like globals()[function_name]. but it is inside a class, so it is not global function, so i cannot use it in this way. How can i do this, i tried globals()[MyModules function_name]() or globals()['MyModules.' function_name](), and it did not work. help me pleease

CodePudding user response:

Running this code in a global scope:

objMyModules = MyModules()
Play_Music = objMyModules.Play_Music

will put Play_Music into global scope with the appropriate function behind it, so that globals()[function_name] will give you the requested result:

class MyModules:
   def Play_Music(self):
     print(123)

function_name = 'Play_Music'

objMyModules = MyModules()
Play_Music = objMyModules.Play_Music

globals()[function_name]() # prints 123
  • Related