Python eleven function parameters

variable parameter

In Python function, variable parameters may also be defined. As the name suggests, the variable parameter is the number of arguments passed is variable, may be . 1 a, 2 two to any number, and it may be 0 a.

We mathematical entitled example, given a set of numbers A , B , C ...... , Calculate A2 + B2 + C2 + ...... .

To define this function, we must determine the parameters entered. Since the number of parameter uncertainty, we can think of the first A , B , C ...... as a list or tuple passed in, this function can be defined as follows:

def calc(numbers):	# numbers 表示 地址
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum

>>> calc([1, 2, 3])
14
>>> calc((1, 3, 5, 7))
84

如果利用可变参数,调用函数的方式可以简化成这样:
>>> calc(1, 2, 3)
14
>>> calc(1, 3, 5, 7)
84
修改函数:
def calc(*numbers):	# 这里相当于C语言指针, *p 代表元素
	    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum

Note : In front of the parameter plus a * number. Inside the function, parameter numbers received is a tuple address, * numbers received is tuple element .

如果已经有一个list或者tuple.
>>> zy = [1,2,3,4,5]
>>> calc(zy)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in calc
TypeError: can't multiply sequence by non-int of type 'list'

The reason being given here is very simple, because calc function parameters received a * nums - received is the element . Pass past a list address is obviously wrong

改正:
>>> calc(*zy)
55

Here on the right, because the function is to receive the element, we have to pass pass element in the collection . * Zy represent the zy this list all the elements as variable parameters to wear into .


Location, default parameters

Python function definition is very simple, but very large degree of flexibility . In addition to the normal definition Required functions, you can also use
   
a default parameter, the variable parameter, and keyword parameters, the interface function is defined such that it not only can handle complex parameters, You can also simplify the code of the caller.


Location parameters :

def power(x):
	return x * x

For Power ( x ) function, the parameter x is a location parameter .


Can Power ( x ) is a modified Power ( x , n ), for calculating x of the n power

def power(x,n):
	s = 1
	while n>0:
		n = n-1
		s = s*x
	return s


The default parameters

New Power ( the X- , the n- ) function definition is no problem, but the old calling code fails because we added a parameter, resulting in old code because of lack of a parameter can not be called normal:


This time, the default parameters on rafts handy. Since we often calculate x is 2 times, therefore, we can put the second parameter n is set to a default value of 2 :

def power(x, n = 2):
	s = 1
	while n>0:
		n=n-1
		s=s*x
	return s

The default parameters should pay attention to a few requirements :
First, the former mandatory parameters, default parameters in the post, otherwise the Python interpreter will complain (think about why the default parameters can not be placed in front of a mandatory parameter); If the default parameters will be placed in front of the election parameters, EG:                                     DEF func ( the n-= 2 , the X- ) :                                         return the n-* the X- so this time, calling func function, following which it will be called so the default parameter a mandatory parameter can not be placed in front?                                     func ( 1 , 3 )                                     FUNC ( 3 ) is the call which it? Second, how to set the default parameters. When the function has a plurality of parameters, the parameters placed in front of a large change, a small change in the parameters put back. Small changes in parameters can be used as the default parameters. What are the benefits of using the default parameters? The greatest advantage is difficult to reduce the function was called.
   



                                   







The default parameters have the biggest pit :


def add_end(L=[]):
    L.append('END')
    return L
…..

add_end()
['END', 'END', 'END']


Python function defined at the time, the default parameter L value was calculated out, i.e., [], because the default parameter L is also a variable that points to the object [], every time the function is called, if the change L of the content, the next call, the default parameters are changed, no longer a function definition [] a.



Define default parameters to keep in mind one thing: the default parameters must point to the same objects!


Solve :

To modify the above example, we can use None of this immutable objects to achieve:

def add_end(L=None):
    if L is None:
        L = []
    L.append('END')
    return L
Keyword arguments

Variable parameters allow you pass 0 or any number of parameters, these parameters are automatically assembled into a variable in the function call tuple . The key parameter allows you pass 0 or any number of parameters including the parameter name, which shut the key word is automatically assembled as a parameter in the internal function dict


>>> def person (name,age,**kw):
...     print('name:',name, 'age:',age, 'other:',kw)
... 
>>> person('gzy',30)
name: gzy age: 30 other: {}
>>> 

>>> person('gzy',33,city='Beijing',gender='M')
name: gzy age: 33 other: {'city': 'Beijing', 'gender': 'M'}

Keyword arguments What is the use? It can extend the functionality of the function. For example, in the person function, we can ensure that the received name and age of these two parameters, however, if the caller is willing to provide additional parameters, we can receive. Imagine you're making a user registration function, in addition to user name and age are required, other options are available, use keyword parameters to define the function will be able to meet the registration requirements.

The variable parameters and the like, may be first assembled a dict , then, to the dict converted into the transmission parameters for a keyword:

>>> extra = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, city=extra['city'], job=extra['job'])
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
当然,上面复杂的调用可以用简化的写法:
>>> extra = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, **extra)
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}


**extra表示把extra这个dict的所有key-value用关键字参数传入到函数的**kw参数,kw将获得一个dict,注意kw获得的dictextra的一份拷贝,对kw的改动不会影响到函数外的extra


命名关键字参数, 参数组合

定义:只接收cityjob的参数,其他,不接收。

def person(name, age, *, city, job): 
print(name, age, city, job)


作用:限制要传入的参数的名字,只能传我已命名关键字参数。(必须要传 * 右边的参数, 参数名也得传, 如果命名关键字参数具有默认值,调用时,可不传入).

特征:命名关键字参数需要一个特殊分隔符*,而后面的参数被视为命名关键字参数


如果要限制关键字参数的名字,就可以用命名关键字参数,例如,只接收cityjob作为关键字参数。这种方式定义的函数如下:

def person(name, age, *, city, job):
    print(name, age, city, job)

和关键字参数**kw不同,命名关键字参数需要一个特殊分隔符**后面的参数被视为命名关键字参数。



命名关键字参数必须传入参数名,这和位置参数不同。如果没有传入参数名,调用将报错:

>>> person('Jack', 24, 'Beijing', 'Engineer')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: person() takes 2 positional arguments but 4 were given

由于调用时缺少参数名cityjobPython解释器把这4个参数均视为位置参数,但person()函数仅接受2个位置参数。



参数组合:

Python中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数,这5种参数都可以组合使用。但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。


发布了149 篇原创文章 · 获赞 68 · 访问量 12万+

Guess you like

Origin blog.csdn.net/m0_37989980/article/details/80644099