SoFunction
Updated on 2025-03-02

Tutorial on the usage example of apply function in Python

1. Overview:

The specific meaning of the python apply function is as follows:
 
apply(func [, args [, kwargs ]]) function is used to indirectly call functions when the function arguments already exist in a tuple or dictionary.. args is a tuple containing the parameters passed by position to be provided to the function. If args is omitted, no arguments are passed, kwargs is a dictionary containing keyword arguments.
 
The return value of apply() is the return value of func(). The element parameters of apply() are ordered, and the order of elements must be consistent with the order of the parameters of func() form.

2. Use examples:

Here are a few examples to explain in detail the usage of apply:

1. Assume that the method without parameters is executed:

def say():
 print 'say in'

apply(say)

The result of the output is 'say in'

2. Functions only have tuple parameters:

def say(a, b):
 print a, b
 
apply(say,("hello", "Zhang San Python"))

The output result is hello, Zhang San python

3. Functions with keyword parameters:

def say(a=1,b=2):
 print a,b
 
def haha(**kw):
 #say(kw)
 apply(say,(),kw)
 
print haha(a='a',b='b')

The output result is: a, b