Home > Backend Development > Python Tutorial > Detailed introduction to function parameters in Python (with examples)

Detailed introduction to function parameters in Python (with examples)

不言
Release: 2018-09-06 17:59:48
Original
3341 people have browsed it

This article brings you a detailed introduction to function parameters in Python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Python's function definition is relatively simple, implemented with the help of the keyword def, but the parameters are very flexible. In addition to the normally defined required parameters, you can also use default parameters, variable parameters, keyword parameters, named keyword parameters, and parameter combinations. This allows the interface defined by the function to not only handle complex parameters, but also simplify calls. The code of the operator

1. Positional parameters

When the function is defined, specify the positional order of the parameters. Positional parameters must be passed in the exact order in the called function definition.

For example: Calculate the nth power of x

def powern(x,n):
    s = 1
    while n >0:
        s = s * x
        n = n -1
    return s
Copy after login

The two parameters x and n are positional parameters. When calling a function, the two passed-in values ​​must be passed in and assigned to the parameters x and n in order of position. If they are omitted by default, an error will be reported. For example:

>>> powern(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: powern() missing 1 required positional argument: 'n'
Copy after login

2. Default parameters

In the function definition, default values ​​are predefined for the parameters. When a function is called, if no specified value is provided for a parameter, the default value is used.
For example: It is still to find the nth power of x, but the default is the 3rd power of x.

def powern( x,n = 3):
    s = 1
    while n >0:
        s = s * x
        n = n -1
    return s
Copy after login

Execution: powern(2), which is equivalent to calling powern(2,3)
If the fourth power of 2 is required, you need to execute: powern(2,4)

What are the benefits of setting default parameters?
Default parameters can simplify function calls and reduce the difficulty of calling functions. Whether it is a simple call or a complex call, only one function needs to be defined.
For example, in the above example of powern(), when other values ​​of n are passed in, other nth powers of x can be realized.

But when using default parameters, there will be pitfalls if used improperly. Let’s first understand the difference between variable parameters and immutable parameters as function parameters:

Immutable parameters as function parameters

>>> a = 1
>>> def func(a):
...     print('func_id:',id(a))
...     a = 2
...     print('after_func_id:',id(a),'id(2):',id(2))
...
>>> print('out_of_func_id:',id(a),'id(1):',id(1))
out_of_func_id: 501962480  id(1): 501962480   # 全局变量a的id
>>> func(a)            # 将全局参数a传入函数
func_id: 501962480    # a=1 的id
after_func_id: 501962496  id(2): 501962496  
>>> print(a)            # 退出函数,a的值仍为1
1
Copy after login

When passing the global a to the function Afterwards, the function automatically copies a copy of the reference. After executing a=2, the memory address of id(a) changes. But it has nothing to do with the outer a.

Variable objects as function parameters

>>> a = []
>>> def func2(a):
...     print('func2_id:',id(a))
...     a.append(1)
...
>>> print('out_of_func2_id',id(a))
out_of_func2_id 59694296
>>> func2(a)
func2_id: 59694296
>>> print(a)
[1]
Copy after login

The type of variable a is list, which is a variable object. The reference of the function points to a mutable object, and the address does not change, so the content of a changes after the function operation.
So when the func2(a) function is operated again, the results are different from the expected results:

>>> func2(a)
func2_id: 59694296    # a地址不变
>>> print(a)
[1, 1]        # 因为第一次执行func2(a)时,已经修改了a=[1],再次调用时,在[1]里新增
Copy after login

For example:

def add_end( L=[] ):  # 设置为一个list变量L(对象可变)
    L.append('end')
    return L
>>> add_end( )
['end']
>>> add_end()  
['end', 'end']
Copy after login

When the default parameters are repeatedly called, the result is incorrect. .
When the Python function is defined, the value of the default parameter L is calculated, which is []. L is also a variable, which points to the object []. Every time the function is called, if the content of L is changed, the content of the default parameter will change the next time it is called, and it will no longer be the [] when the function was defined.
can be changed to:

def add_end( L=None ):  # L为不变对象  
    if L is None:          
    L = []            
    L.append('end')   
    return L
Copy after login

Then no matter how many times it is called, there will be no problem.
So, there is one thing to keep in mind when defining default parameters: Default parameters must point to immutable objects! Because once an immutable object is created, the data inside the object cannot be modified, which reduces errors caused by modifying data. In addition, since the object does not change, reading objects simultaneously in a multi-tasking environment does not require locking.

When setting default parameters, there are several points to note
1. Required parameters come first and default parameters come last, otherwise the Python interpreter will report an error.
two. How to set default parameters? When a function has multiple parameters, put the parameters with greater changes at the front and the parameters with smaller changes at the back. Parameters with small changes can be used as default parameters.
three. Don't use mutable objects as default parameters.

3. Variable parameters *args

Variable parameters, that is, the number of parameters passed in is variable, from 0 to any number.
Because the number of parameters is uncertain, you can use a list or tuple to pass it in. It will then be automatically assembled into a tuple when the function is called.
For example:

def calc(numbers):  # 变量        
    sum = 0               
    for n in numbers:       
        sum = sum + n * n   
    return sum            
>>> calc( [1,2,3] )   # 传入的是一个list
14
Copy after login

Use variable parameters *args:

def calc( *numbers ):  
    sum = 0        
    for n in numbers:    # 在函数内部,numbers组装成一个tuple
    sum = sum + n * n
    return sum
>>> calc( )            # 0个参数  
0
>>> calc( 1,3,5,7 )    # 多个参数 
84
>>> num = [1,2,3]      # list
>>> calc( *num )       # *list –> tuple
14   
>>> t = (1,3,5)
>>> calc( t )          # tuple(错误)  
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 'tuple'
>>> calc( *t )                  
35
Copy after login

The function code remains completely unchanged. However, when calling this function, any number of parameters can be passed in, including 0 parameters.

4. Keyword parameter **kw

Keyword parameter **kw allows passing in 0 to any number of parameters containing parameter names. These keyword parameters Automatically assembled into a dict inside the function. For example:

def person(name , age , **kw ):
    print('name:',name,'age:',age,'other:',kw)
>>> person('xiong',18)
name: xiong age: 18 other: {}
>>> person('xiong',18,city = 'SH')          # city是原本没有的参数,但是因为有**kw
name: xiong age: 18 other: {'city': 'SH'}
Copy after login

What are the key parameters used for? Function functionality can be extended. For example, in the person() function, it is guaranteed to receive the two parameters name and age. But if more parameters are provided, they can also be received. Of course, you can also assemble a dict first, and then convert the dict into keyword parameters and pass it in:

>>> extra ={'city':'shanghai','job':'SET'}                     # dict的定义
>>> person('xiong',18,city = extra['city'],job=extra['job'])   # dict的使用
name: xiong age: 18 other: {'city': 'shanghai', 'job': 'SET'}  # dict的内容
>>> person('xiong',18,**extra)
name: xiong age: 18 other: {'city': 'shanghai', 'job': 'SET'}
Copy after login

[Summary] **extra means passing all the key-values ​​of the extra dict into keyword parameters. The **kw parameter of the function, kw will obtain a dict. Note that the dict obtained by kw is a copy of extra. Changes to kw will not affect the extra outside the function.

五、命名关键字参数

如果要限制关键字参数的名字,就可以用命名关键字参数。需要一个特殊分隔符“”,“”后面的参数被视为命名关键字参数。如果缺少“*”,Python解释器则无法识别位置参数和命名关键字参数。在调用时,必须指定参数名字与参数值。
例如,只接收city和job作为关键字参数,可以使用如下定义:

def person( name ,age,*,city,job):
    print(name , age , city , job )
>>> person('xiong', 18, city='shanghai', job='tester')
xiong 18 shanghai tester
Copy after login

如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了:

>>> def person( name,age,*args,city,job ):     # 此处city和job也是命名关键字参数
...   print(name, age, city, job)
Copy after login

命名关键字参数必须传入参数名,如果没有传入参数名,调用将会报错:

>>> person('xlp',18,'shanghai','tester')          # 错误调用 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: person() missing 2 required keyword-only arguments: 'city' and 'job'
>>> person('xlp',18,city='shanghai',job='tester')  # 正确调用 
xlp 18 shanghai tester
Copy after login

命名关键字参数可以有缺省值,从而简化调用:

>>> def person1(name,age,*,city='shanghai',job):
...   print(name,age,city,job)
...
>>> person1('xlp',18,job='engineer')
xlp 18 shanghai engineer
Copy after login

六、参数组合

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

【总结】

(1)定义可变参数和关键字参数的语法:
*args是可变参数,args接收的是一个list、tuple;
**kw是关键字参数,kw接收的是一个dict;
(2)调用函数时如何传入可变参数和关键字参数的语法:
可变参数直接传入:func(1,2,3)
可变参数间接传入:先组装成list或tuple,l=(1,2,3),再通过args传入,func(l)
关键字参数直接传入:func(a=1,b=2)
关键字参数间接传入:先组装成dict,d={‘a’:1,’b’:2},再通过kw传入,func(d)
(3)命名关键字参数 是为了限制调用者可以传入的参数名,同时可以提供默认值。
(4)定义命名的关键字参数在没有可变参数的情况下,不要忘记写分隔符*,否则定义的将是位置参数

相关推荐:

Python中函数的可变参数

理解Python中函数的参数

The above is the detailed content of Detailed introduction to function parameters in Python (with examples). For more information, please follow other related articles on the PHP Chinese website!

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