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

王林
Release: 2023-09-10 20:49:02
forward
1335 people have browsed it

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

Output

Demo Function 1
Demo Function 2
Copy after login

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')
Copy after login

Output

Called xyzuvw(demo argument)
Called xyzuvw(demo argument)
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template