Python functions are usually called using their names. However, you can also use strings to call functions. To do this, use locals() and globals().
In this example, we will learn how to call two functions using strings -
def demo1(): print('Demo Function 1') def demo2(): print('Demo Function 2') locals()['demo1']() globals()['demo2']()
Demo Function 1 Demo Function 2
In this example, we created a class Example whose function xyzuvw() accepts args and prints them. The globals() function is used to reference this class. Afterwards, getattr() is used to reference the function in the example class xyzuvw() -
class Example: def __init__(self): pass def xyzuvw(self, arg): print('Called xyzuvw({})'.format(arg)) # Using globals() k = globals()['Example']() func = getattr(k, 'xyzuvw') func('demo argument') # Using getarr() getattr(globals()['Example'](), 'xyzuvw')('demo argument')
Called xyzuvw(demo argument) Called xyzuvw(demo argument)
The above is the detailed content of How to use strings to call functions/methods in Python?. For more information, please follow other related articles on the PHP Chinese website!