程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

(Reprinted) about parameter unpacking and parameter passing in Python * and * *

編輯:Python

This article is reprinted from the blogger of the blog park [ Twilight cloud ]
Link to the original text :https://www.cnblogs.com/gongyu2018/p/8805183.html
Thanks to the original author for sharing , The full text is easy to understand , clear . On this basis, this paper makes a supplement

python in * and ** Unpacking and parameter transfer

  • Variable parameters
  • Key parameters
  • Parameter combination
  • summary
  • Reference material

Variable parameters

stay python Function , Variable parameters can be defined . seeing the name of a thing one thinks of its function , Variable parameters are the number of parameters passed in . It can be 1 individual ,2 Or even any of them , It can also be 0 individual .

Illustrate with examples

Give a set of numbers a,b,c…, Calculation a 2 + b 2 + c 2 + . . . a^{2} + b^{2}+c^{2}+... a2+b2+c2+....
To define this function , We have to make sure that Input parameters . However, the number of parameters is uncertain , So we can think about going to a , b , c . . . . a,b,c.... a,b,c.... As a list perhaps tuple Pass it on .
therefore , The function is defined as follows :

def calc(numbers):
sum = 0
for i in range(numbers):
sum = sum + i**2
return sum

But when called , One needs to be assembled first list perhaps tuple

>>> calc([1, 2, 3])
14
>>>calc((1, 3, 4, 5))
51

But we hope , The way to call a function is simpler , For example, this kind of :

>>> calc(1, 2, 3)
14
>>> calc(1, 3, 4, 5)
51

Then we can pass * Change the parameters of the above function to variable parameters :

def calc(*numbers):
sum = 0
for i in range(numbers):
sum = sum + i**2
return sum

Define variable parameters and definitions list or tuple Parameter comparison , Just add one before the parameter * Number . Inside the function , Parameters numbers What was received was a tuple, therefore , The function code is completely unchanged . however , When the function is called , You can pass in any parameter , Include 0 Parameters :

>>> calc(1, 2)
5
>>> calc()
0

The official explanation is as follows :
Function calls require independent positional parameters , But when the argument is in a list or tuple , To do the opposite . for example , Built in range() Function requires independent start and stop Actual parameters . If these parameters are not independent , When calling a function , use * Operators unpack arguments from lists or tuples .

So if there's one list perhaps tuple , What should I do if I need to call it separately without a parameter ?

>>> nums = [1, 2, 3]
>>> calc(nums[0], nums[1], nums[2])
14

This way of writing is certainly feasible , But it's too complicated , therefore Python Allow you to be in list or tuple Add one in front * Number , hold list or tuple The elements of are changed into variable parameters and passed in :

>>> nums = [1, 2, 3]
>>> calc(*nums)
14
 Example 2
>>> arg = [1, 5]
>>> list(range( *arg ))
[1, 2, 3, 4]

Key parameters

Variable parameters allow you to pass in 0 Or any number of parameters , These variable parameters are automatically assembled into a tuple. The keyword parameter allows you to pass in 0 Or any number of parameters with parameter names , These key parameters are automatically assembled into a function dict. See the example :

def person(name, age, **kw):
print ('name:', name, 'age:', age, 'other:', kw)

function person Except for the required parameters name and age Outside , Also accepts keyword parameters kw. When the function is called , Only the required parameters can be passed in :

>>> person('Michael', 30)
name: Michael age: 30 other: {
}

You can also pass in any number of keyword parameters :

>>> person('Bob', 35, city='Beijing')
name: Bob age: 35 other: {
'city': 'Beijing'}
>>> person('Adam', 45, gender='M', job='Engineer')
name: Adam age: 45 other: {
'gender': 'M', 'job': 'Engineer'}

What's the use of keyword parameters ? It can extend the function function . such as , stay person In the function , We guarantee to receive name and age These two parameters , however , If the caller is willing to provide more parameters , We can also receive . Imagine you're doing a user registration function , Except user name and age are required , Everything else is optional , Using the keyword parameter to define this function can meet the registration requirements .

Similar to variable parameters , You can also assemble a dict, then , Take this dict Convert to keyword parameter and pass in :

>>> kw = {
'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, city=kw['city'], job=kw['job'])
name: Jack age: 24 other: {
'city': 'Beijing', 'job': 'Engineer'}

Of course , The above complex calls can be written in a simplified way :

>>> kw = {
'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, **kw)
name: Jack age: 24 other: {
'city': 'Beijing', 'job': 'Engineer'}

Parameter combination

stay Python Define function in , You can use the required parameters 、 Default parameters 、 Variable and key parameters , this 4 All parameters can be used together , Or just some of them , But notice , The order of parameter definitions must be : Required parameters 、 Default parameters 、 Variable parameters and Key parameters .

For example, define a function , Include the above 4 Parameters :

def func(a, b, c=0, *args, **kw):
print 'a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw

When a function is called ,Python The interpreter automatically passes in the corresponding parameters according to the parameter position and parameter name .

>>> func(1, 2)
a = 1 b = 2 c = 0 args = () kw = {
}
>>> func(1, 2, c=3)
a = 1 b = 2 c = 3 args = () kw = {
}
>>> func(1, 2, 3, 'a', 'b')
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {
}
>>> func(1, 2, 3, 'a', 'b', x=99)
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {
'x': 99}

The most amazing thing is through a tuple and dict, You can also call this function :

>>> args = (1, 2, 3, 4)
>>> kw = {
'x': 99}
>>> func(*args, **kw)
a = 1 b = 2 c = 3 args = (4,) kw = {
'x': 99}

therefore , For any function , Can be passed through similar func(*args, **kw) Call it in the form of , No matter how its parameters are defined .

summary

python The function of is very flexible in parameter form , You can implement a simple call , You can also pass in very complex parameters .

The default parameter must be Immutable object , If it's a mutable object , There will be logical errors in the operation !

Pay attention to the syntax of defining variable parameters and keyword parameters :
*args It's a variable parameter , args It received a tuple;
**kw It's a keyword parameter ,kw It received a dict.

And how to pass in the syntax of variable parameters and keyword parameters when calling a function :
Variable parameters can be passed in directly :func(1, 2, 3), You can assemble it first list or tuple, Re pass *args Pass in :func(*(1, 2, 3));
Keyword parameters can be passed in directly :func(a=1, b=2), You can assemble it first dict, Re pass **kw Pass in :func(**{'a': 1, 'b': 2}).

Use *args and **kw yes Python The customary way of writing , Of course, you can also use other parameter names , But it's best to use idioms .

Reference material

The official tutorial :https://docs.python.org/zh-cn/3/tutorial/controlflow.html#unpacking-argument-lists


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved