南京网站建设公司哪家好/seo指搜索引擎
Python 之 函数/函数参数/参数解构 的深入浅出
- 1、函数概念
- 1.1 数学定义
- 1.2 Python 函数
- 1.3 函数的作用
- 2、Python 函数的定义及调用
- 2.1 函数定义
- 2.2 函数调用
- 2.3 函数示例及代码解释
- 2.4 函数返回值说明
- 2.5 函数的销毁
- 3、Python 函数参数及传参方式
- 3.1 传参方式
- 3.2 参数缺省值
- 3.3 可变参数
- 3.3.1 可变位置参数
- 3.3.2 可变关键字参数
- 3.4 keyword-only 参数
- 3.5 参数规则
- 3.6 参数的混合使用
- 4、参数解构
- 4.1 示例1
- 4.2 示例2
- 4.3 示例3
- 4.4 示例4
1、函数概念
1.1 数学定义
- y = f(x)
- y 是 x 的函数, x 是自变量
- y = f(x0, x1……xn)
1.2 Python 函数
- 由若干语句组成的语句块、函数名称、参数列表构成
- 函数是组织代码的最小单元
- 函数能够完成一定的功能
1.3 函数的作用
- 结构化编程对代码的最基本的封装,一般按照功能组织一段代码
- 封装的目的是为了复用,减少冗余代码
- 代码更加简洁美观,可读易懂
2、Python 函数的定义及调用
2.1 函数定义
def 函数名(参数列表):函数体(代码块)[return 返回值]
- 函数名就是标识符,命名要求一样
- 语句块必须缩进,约定4个空格
- Python 的函数若没有 return 语句,会隐式返回一个 None 值
- 定义中的的参数列表成为形式参数,只是一种符号表达(标识符),简称 形参
2.2 函数调用
- 函数定义,只是声明了一个函数,它不能被执行,需要调用执行
- 调用的方式,就是函数名后加上小括号,如果有必要在括号内写上参数
- 调用时写的参数是实际参数,是实实在在传入的值,简称实参
2.3 函数示例及代码解释
def add(x, y): # 函数定义,创建一个标识符 add 指向 函数对象result = x + y # 函数体return result # 返回值 out = add(4, 5) # 函数调用,可能有返回值,使用变量接收这个返回值
print(out) ## print函数加上括号也是调用9
上面代码解释:
-
定义一个函数 add,及函数名是 add,接受两个参数
-
该函数计算的结果,通过返回值返回,需要 return 语句
-
调用时,通过函数名 add 后加 2 个参数,返回值可使用变量接收
-
函数名也是标识符,返回值也是值
-
定义需要在调用前,也就是说调用时,已经被定义过了,否则会有 NameError 异常
-
函数是 可调用的对象, callable()
Signature: callable(obj, /) Docstring: Return whether the object is callable (i.e., some kind of function).Note that classes are callable, as are instances of classes with a __call__() method. Type: builtin_function_or_method
print(callable(add)) callable(add1)
True --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-6-f9248a1bfb76> in <module>1 print(callable(add)) ----> 2 callable(add1)NameError: name 'add1' is not defined
callable(add), callable(1), callable('2')(True, False, False)
2.4 函数返回值说明
- Python 函数使用 return 语句返回 “返回值”
- 所有函数都有返回值,如果没有 return 语句,隐式调用 return None
- return 语句并不一定是函数的语句块的最后一条语句
- 一个函数可以存在多个 return 语句,但是只有一条可以被执行,如果没有一条 return 语句被执行到,则隐式调用 return None
def fn(x):for i in range(x):if i > 3:return ielse:print('{} is greater than 3'.format(x))print('First >>> ', fn(5))
print('Second >>> ', fn(3))First >>> 4
3 is greater than 3
Second >>> None
-
如果有必要,可以显示调用 return None,可以简写为 return
-
如果函数执行了 return 语句,函数就会被返回,当前执行的 return 语句之后的其它语句就不会被执行了
-
返回值的作用:结束函数调用,返回 ‘返回值’
-
函数不能返回多个值,如果有多个值时,隐式的被 Python 封装成了 一个元组
def showconfigs():return 1, 2, 3a = showconfigs() print(a, type(a))(1, 2, 3) <class 'tuple'>
2.5 函数的销毁
- 定义一个函数就是生成一个函数对象,函数名指向的就是函数对象
- 可以使用 del 语句删除函数,使其引用计数减 1
- 可以使用同名标识符覆盖原有定义,本质上也是使其引用计数减 1
- Python程序结束时,所有对象销毁
- 函数也是对象,也不例外,是否销毁,还是看其引用计数是否减为0
3、Python 函数参数及传参方式
- 函数在定义时,要约定好形式参数,调用时也提供足够的实际参数,一般来说,形参和实参个数要保持一致(可变参数除外)。
3.1 传参方式
-
位置传参
定义时 def f(x, y, z),调用时使用 f(x, y, z) 按照参数定义顺序传入实参
-
关键字传参
定义时 def f(x, y, z),调用时使用 f(x=1, y=2, z=3) 使用形参的名字来传入实参的方式 关键字传参,按照形参的名称对应 如果使用了形参名字,那么传参顺序就可和定义顺序不同
3.2 参数缺省值
缺省值也成为默认值,可以在函数定义时,为形参增加一个缺省值。其作用为:
- 参数的默认值可以在未传入足够的实参的时候,对没有给定的参数赋值为默认值
- 参数非常多的时候,并不需要用户每次都输入所有的参数,简化函数调用
3.3 可变参数
3.3.1 可变位置参数
- 在形参前使用 * 表示该参数是可变位置参数,可以接受多个实参
- 函数将收集来的实参组织到一个 tuple 中
def add(*nums):print('nums = {}, type(nums) = {}'.format(nums, type(nums)))add = 0for x in nums:add += xreturn add
add(1, 10, 100, 1000, 10000)nums = (1, 10, 100, 1000, 10000), type(nums) = <class 'tuple'>Out:11111
3.3.2 可变关键字参数
- 在形参前使用 ** 表示该形参是可变关键字传参,可以接受多个关键字参数
- 函数将收集来的实参的名称和值,组织到一个 dict 中
def showconfig(**kwargs):print('kwargs = {}, type(kwargs) = {}'.format(kwargs, type(kwargs)))for k, v in kwargs.items():print('{}={} {}'.format(k, v, type(v)), end=', ')showconfig(host='127.0.0.1', port=8080, username='Lee', password= 'Lee')
kwargs = {'host': '127.0.0.1', 'port': 8080, 'username': 'Lee', 'password': 'Lee'}, type(kwargs) = <class 'dict'>
host=127.0.0.1 <class 'str'>, port=8080 <class 'int'>, username=Lee <class 'str'>, password=Lee <class 'str'>,
3.4 keyword-only 参数
-
在 Python 3 之后,新增了 keyword-only 参数
-
keyword-only 参数:在形参定义时,在一个 * 星号之后,或一个可变位置参数之后,出现的普通参数,就已经不是普通的参数了,成为 keyword-only 参数
-
keyword-only 参数,言下之意就是这个参数必须采用关键字传参
-
*星号后所有的普通参数都成了 keyword-only 参数
- kwargs 会尽可能多截获所有关键字传参
3.5 参数规则
参数列表参数的一般顺序是:
- 1、普通参数
- 2、缺省参数
- 3、可变位置参数
- 4、keyword-only 参数(可带缺省值)
- 5、可变关键字参数
注意事项:
- 代码应该易读易懂,而不是为难别人
- 请按照书写习惯定义函数参数
- 定义最常用参数为普通参数,可不提供缺省值,必须由用户提供。注意这些参数的顺序,最常用的先定义
- 将必须使用名称才能使用的参数,定义为 keyword-only 参数,要求必须使用关键字传参
- 如果函数有很多参数,无法逐一定义,可使用可变参数,如果需要知道这些参数的意义,则使用可变关键字参数收集
3.6 参数的混合使用
- 可以同时有位置参数、缺省值参数、可变位置参数和可变关键字传参
- 可变位置参数在形参前使用一个星号 *
- 可变关键字参数在形参前使用两个星号 **
- 可变位置参数和可变关键字参数都可以收集若干个实参,而且是尽可能的收集,可变位置参数收集成一个 tuple,可变关键字参数收集成一个 dict
- 混合使用参数的时候,普通参数需要放到参数列表前面,可变参数要放到参数列表的后面,可变位置参数需要放在可变关键字参数之前
# 定义函数
def fn(x, y, z=3, *args, **kwargs):print('x={}\ny={}\nz={}\nargs={}\nkwargs={}'.format(x, y, z, args, kwargs))
fn(1, 2, 4, 5, 6, a=1, b='abc')x=1
y=2
z=4
args=(5, 6)
kwargs={'a': 1, 'b': 'abc'}
fn(x=1, z=2, y=4, u=5, v=6, a=1, b='abc')x=1
y=4
z=2
args=()
kwargs={'u': 5, 'v': 6, 'a': 1, 'b': 'abc'}
fn(x=1, y=4, u=5, v=6, a=1, b='abc')x=1
y=4
z=3
args=()
kwargs={'u': 5, 'v': 6, 'a': 1, 'b': 'abc'}
fn(1, y=4, u=5, v=6, a=1, b='abc')x=1
y=4
z=3
args=()
kwargs={'u': 5, 'v': 6, 'a': 1, 'b': 'abc'}
fn(y=4, u=5, v=6, a=1, b='abc', x=1, z=11)x=1
y=4
z=11
args=()
kwargs={'u': 5, 'v': 6, 'a': 1, 'b': 'abc'}
fn(y=4, u=5, v=6, a=1, b='abc')---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-73-704db71d86ad> in <module>
----> 1 fn(y=4, u=5, v=6, a=1, b='abc')TypeError: fn() missing 1 required positional argument: 'x'
fn(1, 2, y=4, u=5, v=6, a=1, b='abc')---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-75-bb63dd78d564> in <module>
----> 1 fn(1, 2, y=4, u=5, v=6, a=1, b='abc')TypeError: fn() got multiple values for argument 'y'
4、参数解构
- 在给函数提供实参的时候,可以在可迭代对象前使用*或者**来进行结构的解构,提取出其中所有元素作为函数的实参
- 使用*解构成位置传参
- 使用**解构成关键字传参
- 提取出来的元素数目要和参数的要求匹配
4.1 示例1
def add(*iterable):result = 0print(iterable)for x in iterable:result += xreturn resultprint(1, add(1, 2, 3))
print(2, add(*[1, 2, 3]))
print(3, add(*range(5)))
(1, 2, 3)
1 6
(1, 2, 3)
2 6
(0, 1, 2, 3, 4)
3 10
4.2 示例2
4.3 示例3
输入一系列数字,并列举出最小值和最大值。
def maxORmin():max_ = Nonemin_ = Nonenums_int_list = []while True:i = input('Please input a series of numbers:')nums_list = i.replace(',', ' ').split() # list strif nums_list[0] == 'quit':breakfor x in nums_list:n = int(x)nums_int_list.append(n)if max_ is None:max_ = nmin_ = nif n > max_:max_ = nif n < min_:min_ = nprint('The numbers you put is {}.\nThe max number is {}.\nThe min number is {}.'.format(nums_int_list, max_, min_))
maxORmin()Please input a series of numbers:1, 2, 4, 7, 1, 1, 2 11
The numbers you put is [1, 2, 4, 7, 1, 1, 2, 11].
The max number is 11.
The min number is 1.
Please input a series of numbers:quit
4.4 示例4
输入一系列数字,并列举出最小值和最大值。
def maxORmin():while True:i = input('Please input a series of numbers:')nums_list = i.replace(',', ' ').split() # list strif nums_list[0] == 'quit':breaknums_int_list = [int(x) for x in nums_list]print('The numbers you put is {}.\nThe max number is {}.\nThe min number is {}.'.format(nums_int_list, max(nums_int_list), min(nums_int_list)))
maxORmin()Please input a series of numbers:6, 2, 3 1 3 11 23 222 111
The numbers you put is [6, 2, 3, 1, 3, 11, 23, 222, 111].
The max number is 222.
The min number is 1.
Please input a series of numbers:quit