Function parameters 07-02

[TOC]

Types of actual parameter describes a

Illustration: spoof 05
Function parameters 07-02

Function parameters and actual parameters are divided into form, referred to as formal and actual parameters:

Parameter i.e. parameter defining a function, the statement in parentheses. It is essentially a parameter variable name, for receiving the transmitted external value.

That argument when calling the function, the incoming values ​​in parentheses, the value may be a combination of constants, variables, or three expressions:

#1:实参是常量
res=my_min(1,2)

#2:实参是变量
a=1
b=2
res=my_min(a,b)

#3:实参是表达式
res=my_min(10*2,10*my_min(3,4))

#4:实参可以是常量、变量、表达式的任意组合
a=2
my_min(1,a,10*my_min(3,4))

There are parameters in the calling function, the argument (value) will be assigned to the parameter (variable names). In Python, variable names and values ​​simply binding relationship, and for a function, this only takes effect when the binding relationship between function calls, released at the end of the call.

Illustration: spoof 06

Figure 06 spoof

Dimorphic participating argument specific use

2.1 positional parameters

I.e. the order of the position, the position parameter refers to parameters defined order, need to see from two perspectives:

  1. When defining the function, in order from left to right in turn defined parameter, called the position parameter, who in this parameter must be defined in the form transmitted value

    >>> def register(name,age,sex): #定义位置形参:name,age,sex,三者都必须被传值
    ...     print('Name:%s Age:%s Sex:%s' %(name,age,sex))
    ... 
    >>> register() #TypeError:缺少3个位置参数
  2. When calling the function, in order from left to right in turn defined argument, called the position of arguments, all participants in this solid form is defined according to the order of left to right correspond to the parameter

    >>> register('lili',18,'male') #对应关系为:name=’lili’,age=18,sex=’male’
    Name:lili Age:18 Sex:male

Illustration: spoof 07
Function parameters 07-02

2.2 Keyword parameters

When calling a function, the argument may be in the form of key = value of the parameter known as keywords, all the arguments in this form definition, can not be completely defined in the order from left to right, but still specified shape parameter assignment

>>> register(sex='male',name='lili',age=18)
Name:lili Age:18 Sex:male

Note that when calling the function, the argument may be mixed by location or by keyword, but must ensure a keyword parameter rear position parameters, may be repeated without assignment to a parameter

>>> register('lili',sex='male',age=18) #正确使用
>>> register(name='lili',18,sex='male') #SyntaxError:关键字参数name=‘lili’在位置参数18之前
>>> register('lili',sex='male',age=18,name='jack') #TypeError:形参name被重复赋值

Illustration: spoof 08
Function parameters 07-02

## 2.3 default parameters

Defining a function, it has been assigned to the reference shape, such parameter called the default parameters, when a plurality of function parameters, need to change parameter values ​​are often defined as the position parameter and the parameter value changes less defined default parameters. For example write a function of student registration information, sex if most students are male, it can be defined as a parameter sex default parameters

>>> def register(name,age,sex='male'): #默认sex的值为male
...     print('Name:%s Age:%s Sex:%s' %(name,age,sex))
...

Has been assigned to the definition of the parameters sex, sex may not mean an assignment when called, which reduces the complexity of function calls

>>> register('tom',17) #大多数情况,无需为sex传值,默认为male
Name:tom Age:17 Sex:male
>>> register('Lili',18,'female') #少数情况,可以为sex传值female
Name:Lili Age:18 Sex:female

Illustration: Figure 09 spoof
Function parameters 07-02

requires attention:

  1. After the default parameters must be in the position parameter
  2. The default parameter values ​​are assigned only once in the function definition phase
>>> x=1
>>> def foo(arg=x):
...     print(arg)
... 
>>> x=5 #定义阶段arg已被赋值为1,此处的修改与默认参数arg无任何关系
>>> foo()
1
  1. The default value of the parameter should normally be set immutable type

    >>> def foo(n,arg=[]):
    ...     arg.append(n)
    ...     return arg
    ... 
    >>> foo(1)
    [1]
    >>> foo(2)
    [1, 2]
    >>> foo(3)
    [1, 2, 3]

    Each time a call is on the same list on the basis of the value added, to read as follows

    >>> def foo(n,arg=None):
    ...     if arg is None:
    ...         arg=[]
    ...     arg.append(n)
    ...     return arg
    ... 
    >>> foo(1)
    [1]
    >>> foo(2)
    [2]
    >>> foo(3)
    [3]

Illustration: spoof 10
Function parameters 07-02

Variable length parameter ## 2.4 (* and ** usage)
Function parameters 07-02

参数的长度可变指的是在调用函数时,实参的个数可以不固定,而在调用函数时,实参的定义无非是按位置或者按关键字两种形式,这就要求形参提供两种解决方案来分别处理两种形式的可变长度的参数

2.4.1 可变长度的位置参数

如果在最后一个形参名前加号,那么在调用函数时,溢出的位置实参,都会被接收,以元组的形式保存下来赋值给该形参

>>> def foo(x,y,z=1,*args): #在最后一个形参名args前加*号
...     print(x)
...     print(y)
...     print(z)
...     print(args)
... 
>>> foo(1,2,3,4,5,6,7)  #实参1、2、3按位置为形参x、y、z赋值,多余的位置实参4、5、6、7都被*接收,以元组的形式保存下来,赋值给args,即args=(4, 5, 6,7)

1
2
3
(4, 5, 6, 7)

如果我们事先生成了一个列表,仍然是可以传值给*args的

>>> def foo(x,y,*args):
...     print(x)
...     print(y)
...     print(args)
... 
>>> L=[3,4,5]
>>> foo(1,2,*L) # *L就相当于位置参数3,4,5, foo(1,2,*L)就等同于foo(1,2,3,4,5)
1
2
(3, 4, 5)

插图:恶搞图11
Function parameters 07-02

注意:如果在传入L时没有加*,那L就只是一个普通的位置参数了

>>> foo(1,2,L) #仅多出一个位置实参L
1
2
([1, 2, 3],)

如果形参为常规的参数(位置或默认),实参仍可以是*的形式

>>> def foo(x,y,z=3):
...     print(x)
...     print(y)
...     print(z)
... 
>>> foo(*[1,2]) #等同于foo(1,2)
1
2
3

如果我们想要求多个值的和,*args就派上用场了

>>> def add(*args):
...     res=0
...     for i in args:
...         res+=i
...     return res
... 
>>> add(1,2,3,4,5)
15

插图:恶搞图12
Function parameters 07-02

2.4.2 可变长度的关键字参数

如果在最后一个形参名前加号,那么在调用函数时,溢出的关键字参数,都会被接收,以字典的形式保存下来赋值给该形参

>>> def foo(x,**kwargs): #在最后一个参数kwargs前加**
...     print(x)        
...     print(kwargs)   
... 
>>> foo(y=2,x=1,z=3) #溢出的关键字实参y=2,z=3都被**接收,以字典的形式保存下来,赋值给kwargs
1
{'z': 3, 'y': 2}

如果我们事先生成了一个字典,仍然是可以传值给**kwargs的

>>> def foo(x,y,**kwargs):
...     print(x)
...     print(y)
...     print(kwargs)
... 
>>> dic={'a':1,'b':2} 
>>> foo(1,2,**dic) #**dic就相当于关键字参数a=1,b=2,foo(1,2,**dic)等同foo(1,2,a=1,b=2)
1
2
{'a': 1, 'b': 2}

插图:恶搞图13
Function parameters 07-02

注意:如果在传入dic时没有加**,那dic就只是一个普通的位置参数了

>>> foo(1,2,dic) #TypeError:函数foo只需要2个位置参数,但是传了3个

如果形参为常规参数(位置或默认),实参仍可以是**的形式

>>> def foo(x,y,z=3):
...     print(x)
...     print(y)
...     print(z)
... 
>>> foo(**{'x':1,'y':2}) #等同于foo(y=2,x=1)
1
2
3

如果我们要编写一个用户认证的函数,起初可能只基于用户名密码的验证就可以了,可以使用**kwargs为日后的扩展供良好的环境,同时保持了函数的简洁性。

>>> def auth(user,password,**kwargs): 
...     pass 
...

2.5 命名关键字参数

在定义了**kwargs参数后,函数调用者就可以传入任意的关键字参数key=value,如果函数体代码的执行需要依赖某个key,必须在函数内进行判断

>>> def register(name,age,**kwargs):
...     if 'sex' in kwargs:
...         #有sex参数
...         pass
...     if 'height' in kwargs:
...         #有height参数
...         pass
... 

想要限定函数的调用者必须以key=value的形式传值,Python3提供了专门的语法:需要在定义形参时,用作为一个分隔符号,号之后的形参称为命名关键字参数。对于这类参数,在函数调用时,必须按照key=value的形式为其传值,且必须被传值

>>> def register(name,age,*,sex,height): #sex,height为命名关键字参数
...     pass
... 
>>> register('lili',18,sex='male',height='1.8m') #正确使用
>>> register('lili',18,'male','1.8m') # TypeError:未使用关键字的形式为sex和height传值
>>> register('lili',18,height='1.8m') # TypeError没有为命名关键字参数height传值。

插图:恶搞图14
Function parameters 07-02

Named keyword parameter can have a default value, which simplifies call

>>> def register(name,age,*,sex='male',height):
...     print('Name:%s,Age:%s,Sex:%s,Height:%s' %(name,age,sex,height))
... 
>>> register('lili',18,height='1.8m')
Name:lili,Age:18,Sex:male,Height:1.8m

It is emphasized that: sex is not the default parameters, height nor positional parameters, because both the post, so the keyword is named parameters, parameters, sex = 'male' part of the default parameter value of the named key, so even there will not be problems put before the parameter height. Further, if there is already a parameter args the named key parameters no longer need for a separate * as a delimiter

>>> def register(name,age,*args,sex='male',height):
...   print('Name:%s,Age:%s,Args:%s,Sex:%s,Height:%s' %(name,age,args,sex,height))
... 
>>> register('lili',18,1,2,3,height='1.8m') #sex与height仍为命名关键字参数
Name:lili,Age:18,Args:(1, 2, 3),Sex:male,Height:1.8m

Illustration: 15 spoof, spoof 16
Function parameters 07-02

Function parameters 07-02

2.6 in combination

To sum up all parameters can be used in any combination, but the order must be defined: positional parameters, default parameters, * args, named keyword arguments, ** kwargs

* Args variable parameter keyword parameters * kwargs usually used in combination, if the parameter is a function of shape args and ** kwargs, then on behalf of the function can be received in any form, of any length parameters

>>> def wrapper(*args,**kwargs):
...     pass
...

Illustration: spoof 17
Function parameters 07-02

This function can also be within the received argument to another function (which would be an asset to achieve decorator section 4.6)

>>> def func(x,y,z):
...     print(x,y,z)
... 
>>> def wrapper(*args,**kwargs):
...     func(*args,**kwargs)
...
>>> wrapper(1,z=3,y=2)
1 2 3

According to the above wording, when the wrapper as a function of mass participation, in fact, follow the rules of the parameters of function func, call the function wrapper procedure is as follows:

  1. Position * 1 is received argument, preserved in the form of tuples, assigned to args, i.e. args = (1,), Keyword argument z = 3, y = 2 ** are received, saved in the form of a dictionary , assigned to kwargs, i.e. kwargs = { 'y': 2, 'z': 3}
  2. Performing FUNC ( args, kwargs), i.e. func (* (1,), ** { 'y': 2, 'z': 3}), is equivalent to func (1, z = 3, y = 2)
提示: *args、**kwargs中的args和kwargs被替换成其他名字并无语法错误,但使用args、kwargs是约定俗成的。

Illustration: spoof 18
Function parameters 07-02

Guess you like

Origin blog.51cto.com/egon09/2461519
Recommended