前言
在Python里面常规有两种参数,位置参数和关键词参数,当需要不固定参数的场景时候就需要使用可变位置参数和可变关键字参数。
一、位置参数和关键词参数
- 位置参数: 位置参数的参数必须按顺序传递
def say_hello(name, age):
print(f"hello, {name}, your age is {age}")
say_hello("Andy", 14)
- 关键字参数: 关键字参数通过关键字=参数的格式传递,可以不按顺序传递
def say_hello(name, age):
print(f"hello, {name}, your age is {age}")
say_hello(age=12, name="Andy")
- 默认参数:除了以上,还有默认参数的场景,此时参数已经传递了默认值,如果不传参,则的到默认值
def say_hello(name, age=14):
print(f"hello, {name}, your age is {age}")
say_hello("Andy")
二、可变参数
- 可变位置参数:可变位置参数通过
*args
传递,传递后得到的args是一个元组。
def say_hello(name, age, *args):
print(f"hello, {name}, your age is {age}, extra args is {args}")
say_hello("Andy", 18, 1, 2, 3)
# 输出: hello, Andy, your age is 18, extra args is (1, 2, 3)
- 可变关键字参数:可变关键字参数通过
**kwargs
传递,传递后得到kwargs 是一个字典。
def say_hello(name, age, *args, friend="Tom", friend_age=14, **kwargs):
print(f"hello, {name}, your age is {age}, extra args is {args}, extra kwargs is {kwargs}")
say_hello("Andy", 18, 1, 2, 3, friend="Jack", friend_age=12, interest="badminton", food="origin")
# 输出为: hello, Andy, your age is 18, extra args is (1, 2, 3), extra kwargs is {'interest': 'badminton', 'food': 'origin'}
通过定义def say_hello(name, age, *args, **kwargs)
函数,实现函数参数可变性,此时args
和kwargs
都可以是空,实现函数调用的灵活性。使用场景包括装饰器(wrapper(*args, **kwargs)),在执行函数包含参数时候调用装饰器使用可变参数传递。
总结
以上就是位置参数,关键字参数,以及可变参数的使用,方便在函数调用的参数使用的灵活性。