mobile wallpaper 1
mobile wallpaper 2
mobile wallpaper 3
mobile wallpaper 4
295 words
1 minute
函数与函数式编程
2026-10-18

1. 函数#

1.1 概念#

  • 为了实现模块化,Python 允许将大量的程序分解为多个函数来实现。
  • Python 使用 def 来自定义函数。
def 函数名(参数):
"""函数_文档字符串"""
函数语句
return [表达式]

1.2 参数传递#

  • 参数有两种:
    • 形参:函数定义时规定接收的参数。
    • 实参:调用函数时传入的实际参数。

1. 形参#

  • 设置形参的方式:
    • 只指定参数名:func(first, second)
    • 指定默认参数值:func(first='hello', second='world')
    • * 收集参数到元组:func(*args);func('hello', 'world')
    • ** 收集参数到字典:func(**kwargs);func(first='hello', second='world')

2. 实参#

  • 实参传递的方式:
    • 位置参数:func('hello', 'world')
    • 关键字参数:func('hello', second='world')

2. 作用域#

  • 变量可以视为指向值的名称,在不同的空间中变量名对应的值可能不一样,这个空间称为命名空间或作用域。
  • 作用域分为两种:
    • 全局作用域:定义该函数的模块。
    • 局部作用域:每次执行函数时创建的作用域,包含函数参数名称和函数体内赋值的变量名称。

3. lambda 运算符#

  • 使用 lambda 语句可以创建表达式形式的匿名函数:lambda args: expression。
a = lambda x, y: x + y
r = a(2, 3)
Share

If this article helped you, please share it with others!

函数与函数式编程
https://kieas.cn/posts/python-functions/
Author
Kieas
Published at
2026-10-18
License
CC BY-NC-SA 4.0

Some information may be outdated

Table of Contents