
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
How do I use strings to call functions/methods in Python?
Python Functions are generally called using their name. However, you can also use strings to call functions. For that, use the locals() and globals().
Call functions using strings
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 a function using string variable
Example
In this example, we have created a class Example with the function xyzuvw() that accepts arg and print them. The globals() function is used to refer to the class. After that, the getattr() is used to refer to function xyzuvw() within class Example −
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)
- Related Articles
- How to use arrow functions used as methods in JavaScript?
- How to call functions in JavaScript?
- How do I enumerate functions of a Python class?
- How do I create documentation from doc strings in Python?
- How do I use method overloading in Python?
- How do I get list of methods in a Python class?
- How to call custom methods in C#?
- How do I chain methods in PHP?
- How do I compare strings in Java?
- How do I write a function with output parameters (call by reference) in Python?
- Built-in List Functions & Methods in Python
- Built-in Dictionary Functions & Methods in Python
- How to call C++ functions from Java?
- How do I create static class data and static class methods in Python?
- How do nested functions work in Python?

Advertisements