Home  >  Article  >  Backend Development  >  How to use strings to call functions/methods in Python?

How to use strings to call functions/methods in Python?

王林
王林forward
2023-09-10 20:49:021288browse

How to use strings to call functions/methods in Python?

Python functions are usually called using their names. However, you can also use strings to call functions. To do this, use locals() and globals().

Call function using string

Example

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']()

Output

Demo Function 1
Demo Function 2

Call function using string variable

Example

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')

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete