Home > Backend Development > Python Tutorial > Detailed introduction to parameters in python functions

Detailed introduction to parameters in python functions

不言
Release: 2018-10-09 16:33:17
forward
3008 people have browsed it

This article brings you a detailed introduction to the parameters in python functions. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Define functions

Functions in python are defined using the keyword def, in the format:

def 函数名(形参):
    函数语句块
Copy after login

Function names can only contain strings, underscores and Numbers and cannot start with a number.
The formal parameters of the function are divided into: positional parameters, default parameters (parameters with default values), and dynamic parameters.
return is a keyword, which is used to return the result of the function. When return is encountered, the function ends immediately. Then execute other statements

Positional parameters

def func(a,b):
return a,b 
print(func(1,2)) #按照位置传入参数,1赋值给a,2赋值给b
print(func(a=2,b=3))#按照关键字传入参数,指定a、b的值
print(func(3,b=6))#混合传入,此时注意,位置参数要在前面
#如果不指定实参会报错,因为函数中由位置参数,则调用函数时必须传入参数
#print(func())
Copy after login

The output result is:

    (1, 2)
    (2, 3)
    (3, 6)
Copy after login

When no return is written or only return is written, and no other content is written later , the function will return None
return can return a value of any data type. When return returns multiple values, they will be organized into tuples. That is to say, when multiple values ​​are returned, the type is tuple. Multiple variables can be used to receive results, but the number of variables must be the same as the number of returned values. The example is as follows:

def func():
    return 1,'asd',(1,'a',['hello','world']),[1,2,3]
print('直接打印结果:',func())
a,b,c,d = func() 
print('a:',a)
print('b:',b)
print('c:',c)
print('d:',d)
Copy after login

Output:

直接打印结果: (1, 'asd', (1, 'a', ['hello', 'world']), [1, 2, 3])
a: 1
b: asd
c: (1, 'a', ['hello', 'world'])
d: [1, 2, 3]
Copy after login

Default parameters

def func(name,age=20):
    print('{}已经{}岁啦'.format(name,age))
func('刘小姐')#默认参数可以不传,这时age值为默认的20
func('刘小姐',28)#默认参数传值时则覆盖默认值
Copy after login
刘小姐已经20岁啦
刘小姐已经28岁啦
Copy after login

The default value is assigned only once. This makes a difference when the default value is a mutable object, such as a list, dictionary, or instance of most classes. For example, the following function will accumulate the parameters passed to it (previously) during subsequent calls:

def func(a = []):
    a.append('x')
    return a
for i in range(6):
    print(func())
Copy after login

Each time the loop is called, although no parameters are passed to a, a will not be assigned a value. Empty list [], because the default value will only be assigned once, so the output becomes the following:

    ['x']
    ['x', 'x']
    ['x', 'x', 'x']
    ['x', 'x', 'x', 'x']
    ['x', 'x', 'x', 'x', 'x']
    ['x', 'x', 'x', 'x', 'x', 'x']
Copy after login

If you don’t want the default value to accumulate in subsequent calls, you can define it as follows Function:

def func(a = None):
    if a is None: #如果a是None
        a = []
    a.append('x')
    return a
for i in range(6):
    print(func())
Copy after login
['x']
['x']
['x']
['x']
['x']
['x']
Copy after login

Dynamic parameters

Dynamic parameters are divided into two types:
One is represented by *args, which will receive redundant positional parameters uniformly , saved in the form of a tuple
The other is represented by **kwargs, which will receive the redundant keyword parameters uniformly and save them in the form of a dictionary
Let’s look at an example of *args first

def func(a,b,c,*args):
    print('*args内容为:',args)
    sum1 = 0
    for i in args:
        sum1 += i
    sum1 = sum1 + a +b +c
    return sum1
print(func(1,2,3,4,5,6,7,8,9,10))
Copy after login

Although there are only 4 formal parameters, we passed in 10, and 4-10 are all received by *args to form a tuple

    *args内容为: (4, 5, 6, 7, 8, 9, 10)
    55
Copy after login

Let’s take a look at **kwargs

def func(a,b,*args,c=20,**kwargs):
    print('*args内容为:',args)
    print(c)
    print('**kwargs内容为:',kwargs)
    sum1 = 0
    for i in args:
        sum1 += i
    sum1 = sum1 + a +b +c
    for k in kwargs:
        sum1 += kwargs[k]
    return sum1
print(func(1,2,3,4,5,6,7,8,9,10,c=22,x=11,y=33,z=66))
Copy after login
*args内容为: (3, 4, 5, 6, 7, 8, 9, 10)
22
**kwargs内容为: {'x': 11, 'y': 33, 'z': 66}
187
Copy after login
Copy after login

It can be seen from the above example that if various types of formal parameters appear, their order should be: positional parameters, dynamic parameters args, default parameters, dynamic parameters *keargs

Because it is assumed that the default parameter is before args, that is, func(a,b,c=20,args,*kwargs), then when the parameter is passed in, the value of the formal parameter c will be implemented first. Parameter 3 is assigned a value (because the position of 3 corresponds to c, when the default parameter is not assigned, the value is the default, and when assigned, the default value is overwritten). At this time, c=3, but c=20 appears later, and an error will be reported. Because the formal parameter c is assigned twice, which is not allowed, the default parameters are ranked after args.

The default parameters must be ranked before kwargs, because if they are ranked behind, then c=22 will be directly received by kwargs, so the default parameters are meaningless. This is not allowed and an error will be reported.

The following is another way for the default parameters to be ranked in front of *args. This Although this method also yields the same result, you must be particularly careful about the location of the value of c when calling.
Moreover, this method will make the default parameters meaningless, because the default value of 20 is never used. .
So it is appropriate to put the default parameters after *args.

def func(a,b,c=20,*args,**kwargs):
    print('*args内容为:',args)
    print(c)
    print('**kwargs内容为:',kwargs)
    sum1 = 0
    for i in args:
        sum1 += i
    sum1 = sum1 + a +b +c
    for k in kwargs:
        sum1 += kwargs[k]
    return sum1
print(func(1,2,22,3,4,5,6,7,8,9,10,x=11,y=33,z=66))
Copy after login
*args内容为: (3, 4, 5, 6, 7, 8, 9, 10)
22
**kwargs内容为: {'x': 11, 'y': 33, 'z': 66}
187
Copy after login
Copy after login

A quick way to pass dynamic parameters

For *args, you can add * in front of lis when passing in parameters and directly pass in the content

def func(*args):
    return args
lis = [1,2,{3,4,5},6,7,[8,9,0,1,23],34,5,(56,67),78,23]
print(type(lis))
print(func(*lis))
Copy after login
<class &#39;list&#39;>
(1, 2, {3, 4, 5}, 6, 7, [8, 9, 0, 1, 23], 34, 5, (56, 67), 78, 23)
Copy after login

For **kwargs, you can add ** in front of dic when passing in parameters and directly pass in the content

def func(**kwargs):
    return kwargs
dic = {'name':'超人','age':'500','job':'装逼'}
print(func(**dic))
Copy after login
{'name': '超人', 'age': '500', 'job': '装逼'}
Copy after login


The above is the detailed content of Detailed introduction to parameters in python functions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.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