A usage example tutorial for the apply function in Python

  • 2020-04-02 13:52:04
  • OfStack

I. overview:

The python apply function has the following meaning:
 
The apply(func [, args [, kwargs]]) function is used to call a function indirectly when the function argument already exists in a tuple or dictionary. Args is a tuple that contains the arguments passed by position that will be supplied to the function. If args is omitted, no arguments are passed. Kwargs is a dictionary that contains keyword arguments.
 
The return value of apply() is the return value of func(), the element parameters of apply() are ordered, and the order of the elements must be the same as the order of the func() form parameters

Ii. Examples:

Here are some examples of how to use apply in detail:

1. It is assumed that the method without parameters is executed:


def say():
 print 'say in'

apply(say)

The output is 'say in'

2. Parameters of a function with only tuples:


def say(a, b):
 print a, b
 
apply(say,("hello", " Zhang SAN python"))

The output is hello, zhang SAN python

3. Function with keyword parameter:


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 is :a,b


Related articles: