-
必选参数
-
默认参数
-
可变参数
-
关键字参数
必选参数
所谓必选参数,就是在你写函数的时候,规定有些参数必须要写进去,不然就会报错,比如:
>>> def func(name):
... print(f"{name} is a good persion.")
...
>>> func()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: func() missing 1 required positional argument: 'name'
>>>
>>> func('liuning')
liuning is a good persion.
默认参数
所谓默认参数顾名思义,就是一些参数如果你不去写入,就会带给你一个默认的参数值传递到函数内,比如:
>>> def student(name, age, hobby='studying knowadge'):
... print(f"{name}'s age is {age}, and hobby is {hobby}")
...
>>>
>>> student('liuning', 25)
liuning's age is 25, and hobby is studying knowadge
可变参数
可变参数就是指在函数中,当需要传入多个参数并且你不确定参数个数的时候,你就需要用到可变参数。这里传入的可变参数实质上是会生成一个tuple,这里的可变参数需要用*kw表示,比如:
>>> def func1(*numbers):
... sum = 0
... for i in numbers:
... sum = sum + i * i
... print(sum)
...
>>> func1(1, 2, 3)
14
关键字参数
关键字参数就是类似于字典类型的参数存在,使用**kw来表示,用于非必填性的参数。比如在一次自我介绍中要求必须有名字和年龄,但是如果你想多介绍一下自己我们也不会阻拦,例如:
>>> def func3(name, age, **kw):
... print(f"myname is {name}, and {age} yearsold, other: {kw}")
>>>
>>> func3('liuning', 25, hobby1='I like reading',hobby2='I like playing game "LOL"')
myname is liuning, and 25 yearsold, other: {'hobby1': 'I like reading', 'hobby2': 'I like playing game "LOL"'}
网友评论