python中可变函数怎么定义

更新时间:02-04 教程 由 迟暮。 分享

如果我们想要在调用函数时,少输入一些变量。我们可以在定义函数值,输入一些默认的参数值:

defadd(a,b=2,c=3):

returna+b+c

print(add(2))

output:7

1

2

3

4

1

2

3

4

add函数有3个变量,那么我们在定义它的时候,后俩个变量被我们赋予了默认参数值分别是2和3。若没有在调用时,明确给出后俩个变量的参数值,那么python会自动调用默认参数值。

合法调用方式:

add(2),add(2,3),add(2,4,5)

非法定义方式:

defadd(a,b=2,c):

returna+b+c

1

2

3

4

5

1

2

3

4

5

但是要注意,当你定义了第一个变量的默认参数值后,那么后面的变量必须全部都带有默认参数值。

参数量可变的函数定义

在python中有一个∗*∗运算符,来实现可变参数的函数定义。

*的用法,列表的解包:

arg=[2,4]

foriinrange(*arg):

print(i)

字典的解包,直接为函数提供关键字以及参数:

d={'a':1,'b':2,'c':3}

defadd(a,b,c):

returna+b+c

print(add(**d))

output:6

1

2

3

4

5

6

7

8

9

10

1

2

3

4

5

6

7

8

9

10

当存在一个形式为**name的最后一个形参时,它会接收一个字典,其中包含除了与已有形参相对应的关键字参数以外的所有关键字参数。这可以与一个形式为*name,接收一个包含除了与已有形参列表以外的位置参数的元组的形参组合使用(*name必须出现在**name之前。)例如,如果我们这样定义一个函数:

defcheeseshop(kind,*arguments,**keywords):

print("--Doyouhaveany",kind,"?")

print("--I'msorry,we'realloutof",kind)

forarginarguments:

print(arg)

print("-"*40)

forkwinkeywords:

print(kw,":",keywords[kw])

1

2

3

4

5

6

7

8

1

2

3

4

5

6

7

8

我们可以这样去调用它:

cheeseshop("Limburger","It'sveryrunny,sir.",

"It'sreallyvery,VERYrunny,sir.",

shopkeeper="MichaelPalin",

client="JohnCleese",

sketch="CheeseShopSketch")

1

2

3

4

5

1

2

3

4

声明:关于《python中可变函数怎么定义》以上内容仅供参考,若您的权利被侵害,请联系13825271@qq.com
本文网址:http://www.25820.com/tutorial/14_2104215.html