07_函数进阶
7.1 函数多返回值
1、思考
2、多个返回值
def test_info():
return 1, "hello", True
x, y, z = test_info()
print(x)
print(y)
print(z)
7.2 函数多种传参方式
1、函数的参数种类
使用方式
上的不同,函数有4种常见参数使用方式:
- 位置参数
- 关键字参数
- 缺省参数
- 不定长参数
2、位置参数
3、关键字参数
4、缺省参数
5、不定长参数
①位置传递
# 不定长参数
# 位置传递
def test_func(*args):
print(f"参数类型是{type(args)}, 参数内容是{args}")
test_func() # 参数类型是<class 'tuple'>, 参数内容是()
test_func(1) # 参数类型是<class 'tuple'>, 参数内容是(1,)
test_func("hello", 20, True) # 参数类型是<class 'tuple'>, 参数内容是('hello', 20, True)
②关键字传递
# 关键字传递
def user_info(**kwargs):
print(f"参数类型是{type(kwargs)}, 参数内容是{kwargs}")
user_info() # 参数类型是<class 'dict'>, 参数内容是{}
user_info(age=20) # 参数类型是<class 'dict'>, 参数内容是{'age': 20}
user_info(age=20, name="晓丽", gender="女") # 参数类型是<class 'dict'>, 参数内容是{'age': 20, 'name': '晓丽', 'gender': '女'}
6、总结
7.3 匿名函数
1、函数作为参数传递
在前面的函数学习中,我们一直使用的函数,都是接受数据作为参数传入:数字、字符串、字典、列表、元组等。
其实,我们学习的函数本身,也可以作为参数传入另一个函数内。
def test_func(compute):
result = compute(1, 2)
print(result)
def compute(x, y):
return x + y
test_func(compute) # 3
小结:1、函数本身是可以作为参数,传入另一个函数中进行使用的。2、将函数传入的作用在于:传入计算逻辑,而非传入数据。
2、lambda匿名函数
# lambda匿名函数
def test_func(compute):
result = compute(1, 2)
print(result)
test_func(lambda x, y: x - y) # -1