Skip to Content
Python语言及其应用(第2版)
book

Python语言及其应用(第2版)

by Bill Lubanovic
March 2022
Intermediate to advanced
522 pages
13h 52m
Chinese
Posts & Telecom Press
Content preview from Python语言及其应用(第2版)
函数
131
可以将此与
*args
**kwargs
技术配合使用。
下面来定义一个测试函数,该函数能够接受任意数量的位置实参,使用
sum()
函数计算这
些实参之和并将其返回:
>>> def sum_args(*args):
... return sum(args)
前面还未讲过
sum()
。它是
Python
的一个内建函数,用来计算可迭代的数值(整型或者浮
点型)参数之和。
定义一个新函数
run_with_positional_args()
,该函数可以接受一个函数和任意数量的位
置实参:
>>> def run_with_positional_args(func, *args):
... return func(*args)
调用该函数:
>>> run_with_positional_args(sum_args, 1, 2, 3, 4)
10
你可以使用函数作为列表、元组、集合以及字典的元素。由于函数是不可变的,因此也可
以将其用作字典的键。
9.6
内部函数
可以在一个函数的内部定义另一个函数。
>>> def outer(a, b):
... def inner(c, d):
... return c + d
... return inner(a, b)
...
>>>
>>> outer(4, 7)
11
如果需要在另一个函数内执行多次复杂任务,则内部函数非常有用,可以避免循环或重复
代码。在下列字符串示例中,内部函数为其参数添加了一些文本。
>>> def knights(saying):
... def ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano
Python实用技能学习指南

Python实用技能学习指南

Posts & Telecom Press, Robert Smallshire, Austin Bingham
Python技术基础视频教程

Python技术基础视频教程

保罗·J·戴特尔
Python面向对象编程指南

Python面向对象编程指南

Posts & Telecom Press, Steven F. Lott

Publisher Resources

ISBN: 9787115586223