Advanced functions
1.8 Advanced functions
1.8.1 The function is passed in as a parameter
1. Introduction: The function is passed as a range to the function for operation
2. The function is passed into the function as a parameter
3. The difference between function calling and logic passing
- One is passed in as data, but the function to be called must be
- One is called as logic, but the data to be called must be
4. Reference code
# 函数传入函数
# 定义一个函数,接收另一个函数作为传入参数
def test_func(com):
result=com(1,2)
print(f"com计算的结果为:{result}")
print(f"计算类型为,{type(com)}")
# 定义一个函数作为准备进行传入另外一个函数中
# a+b的函数
def add(a,b):
return a+b;
# a-b的函数
def rem(a,b):
return a-b;
# 调用,传入函数
test_func(add)
test_func(rem)
At this time, the function may not be fixed, but the internal data may be fixed. The value passed in is the name of the function
1.8.2 lambda anonymous function
- The function originally defined by def has a name
- Functions defined by lambda can have no name
1. How the lambda function is defined
3. Define the function as an anonymous function
- Can only be used temporarily once. because there is no name
- def can be used repeatedly with a name
benefit:
- concise
- convenient
# lambda函数
def test_func(add):
result=add(1,2)
print(f"add的结果为,{result}")
# 采用匿名函数的方式定义add函数
# 前面是参数的定义,后面的是对应的函数的定义,注意点的点在于计算的逻辑必须是一行的
test_func(lambda x,y:x+y)
summary
1.8.3 Multiple return values of functions
- Separated by multiple commas, multiple parameters are received
1. Basic grammar
2. Case
# 函数的多返回值
# 逗号分开
def func(a,b):
return a+b,a-b,a*b,a/b
a,b,c,d=func(1,2)
print(a)
print(b)
print(c)
print(d)
1.8.4 Multiple ways of passing parameters to functions
1. Positional parameters
- It is to pass the value of the parameter according to the position of the parameter. This is the most basic way to use the function.
2. Keyword arguments
- Can not be limited by location
- Pass parameters in the form of key-value pairs
- Must be in the last place, note.
- For parameters that are not specified, you can specify them arbitrarily
# 参数的传递的方式
def func(name,age ,gender):
print(f"{name},今年,{age},岁,性别,{gender}")
# 默认的方式
func("小米",20,"男")
# 关键字参数
# 不受到顺序的限制
func(age=20,gender="男",name="小米")
# 关键字和默认的混用
func("小米",20,"男")
# 设置函数的默认值
def func(name,age ,gender="男"):
print(f"{name},今年,{age},岁,性别,{gender}")
4. Variable length parameters
- The default is in the form of tuples
# 位置的不定长
# 采用的是元组的不定长的形式
def test(*args):
print("位置不定长的参数:",end='')
print(args)
print(f"类型是,{type(args)}")
test(1,2,3,4)
#关键字的不定长
# 采用的是字典的不定长的传入的形式
def testx(**x):
print("位置不定长的参数:",end='')
print(f"类型是,{type(x)}")
print(x)
testx(id=1,name='张三',age=12,sex='男')
summary: