Python函数从入门到进阶
一、函数基础
1.1 什么是函数?
函数就是把一段代码打包成一个整体,可以重复使用。
python
# 没有函数:每次都要写一遍
print("hello")
print("hello")
print("hello")
# 有函数:只需定义一次,可以反复调用
def say_hello():
print("hello")
say_hello() # 调用
say_hello() # 再调用
优点:
-
代码复用,不用重复写
-
代码更清晰,容易理解
-
方便修改和维护
1.2 函数的定义与调用
python
# 定义函数
def greet():
print("你好!")
# 调用函数
greet() # 输出:你好!
带参数的函数:
python
def greet(name):
print(f"你好,{name}!")
greet("小明") # 输出:你好,小明!
1.3 函数的返回值
用 return 返回结果:
python
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 8
没有 return 返回 None:
python
def say():
print("hello")
result = say() # 输出 hello
print(result) # None
二、函数的参数
2.1 位置参数
按顺序传参,位置不能乱:
python
def info(name, age):
print(f"姓名:{name},年龄:{age}")
info("小明", 18) # 正确
info(18, "小明") # 错误!类型不对
2.2 默认参数
给参数设置默认值,调用时可以不传:
python
def greet(name, msg="你好"):
print(f"{msg},{name}!")
greet("小明") # 你好,小明!
greet("小红", "早上好") # 早上好,小红!
2.3 关键字参数
指定参数名传参,顺序可以乱:
python
def info(name, age):
print(f"姓名:{name},年龄:{age}")
info(age=18, name="小明") # 姓名:小明,年龄:18
2.4 可变参数
*args:接收任意多个位置参数(打包成元组)
python
def sum_all(*args):
total = 0
for num in args:
total += num
return total
print(sum_all(1, 2, 3)) # 6
print(sum_all(1, 2, 3, 4, 5)) # 15
**kwargs:接收任意多个关键字参数(打包成字典)
python
def show_info(**kwargs):
for key, value in kwargs.items():
print(f"{key} = {value}")
show_info(name="小明", age=18, city="北京")
# name = 小明
# age = 18
# city = 北京
2.5 参数解包
把列表或字典拆开作为参数传入:
python
# 列表解包(用 *)
nums = [10, 20]
def add(a, b):
return a + b
print(add(*nums)) # 30
# 字典解包(用 **)
data = {"name": "小明", "age": 18}
def info(name, age):
print(f"{name},{age}岁")
info(**data) # 小明,18岁
三、变量作用域
3.1 局部变量与全局变量
python
# 全局变量(函数外)
x = 10
def test():
# 局部变量(函数内)
y = 20
print(x) # 可以访问全局变量
print(y) # 可以访问局部变量
test()
print(x) # 可以访问
print(y) # 报错!局部变量函数外不能访问
3.2 global 与 nonlocal
global:在函数内修改全局变量
python
x = 10
def test():
global x
x = 20 # 修改全局变量
test()
print(x) # 20
nonlocal:在内层函数修改外层函数的变量
python
def outer():
x = 10
def inner():
nonlocal x
x = 20 # 修改外层函数的 x
inner()
print(x) # 20
outer()
3.3 globals() 与 locals()
-
globals():查看所有全局变量 -
locals():查看所有局部变量
python
x = 10
y = 20
def test():
a = 1
b = 2
print(locals()) # {'a': 1, 'b': 2}
test()
print(globals()) # {'x': 10, 'y': 20, ...}
四、特殊函数
4.1 匿名函数(lambda)
一句话函数,适合简单操作:
python
# 普通函数
def add(a, b):
return a + b
# 匿名函数(等价)
add = lambda a, b: a + b
print(add(3, 5)) # 8
常用场景:
python
nums = [1, 5, 3, 9, 2] # 按数字大小排序 nums.sort(key=lambda x: x) print(nums) # [1, 2, 3, 5, 9]
4.2 高阶函数
把函数当参数传递:
python
def greet(name):
return f"你好,{name}"
def say_hello(func, name):
print(func(name))
say_hello(greet, "小明") # 你好,小明
常用高阶函数:
python
# map:对每个元素执行函数 nums = [1, 2, 3, 4] result = list(map(lambda x: x*2, nums)) print(result) # [2, 4, 6, 8] # filter:过滤 nums = [1, 2, 3, 4, 5] result = list(filter(lambda x: x > 3, nums)) print(result) # [4, 5]
4.3 递归函数
函数调用自己:
python
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)
print(factorial(5)) # 120
递归三要素:
-
终止条件(n == 1)
-
调用自己(factorial(n-1))
-
组合结果(n * ...)
五、进阶技巧
5.1 闭包
函数内部定义函数,并返回内部函数:
python
def outer(x):
def inner(y):
return x + y
return inner
add = outer(10)
print(add(5)) # 15
print(add(20)) # 30
特点:内部函数记住了外层函数的变量 x。
5.2 装饰器
在不修改原函数的情况下,增加功能:
python
def timer(func):
import time
def wrapper():
start = time.time()
func()
end = time.time()
print(f"耗时:{end - start}秒")
return wrapper
@timer
def test():
time.sleep(1)
print("执行完毕")
test()
# 执行完毕
# 耗时:1.000秒
本质:test = timer(test)
5.3 装饰器常用案例
1. 计时器
python
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} 耗时 {time.time() - start:.2f}秒")
return result
return wrapper
@timer
def sleep_test():
time.sleep(1)
sleep_test() # sleep_test 耗时 1.00秒
2. 日志记录
python
def logger(func):
def wrapper(*args, **kwargs):
print(f"调用函数:{func.__name__}")
print(f"参数:{args}, {kwargs}")
result = func(*args, **kwargs)
print(f"返回值:{result}")
return result
return wrapper
@logger
def add(a, b):
return a + b
add(3, 5)
# 调用函数:add
# 参数:(3, 5), {}
# 返回值:8
3. 权限验证
python
def login_required(func):
def wrapper(user, *args, **kwargs):
if user.get("is_login"):
return func(user, *args, **kwargs)
else:
print("请先登录")
return wrapper
@login_required
def profile(user):
print("个人资料页面")
profile({"is_login": True}) # 个人资料页面
profile({"is_login": False}) # 请先登录
总结
| 内容 | 要点 |
|---|---|
| 函数定义 | def 函数名(): |
| 返回值 | return |
| 位置参数 | 按顺序传 |
| 默认参数 | 有默认值 |
| 关键字参数 | 指名道姓 |
*args | 收多个位置参数 |
**kwargs | 收多个关键字参数 |
| global | 修改全局变量 |
| lambda | 匿名函数 |
| 递归 | 函数调用自己 |
| 闭包 | 函数里返回函数 |
| 装饰器 | 给函数加功能 |
学习建议:从基础开始,多写代码练习,逐步掌握!😊
496



被折叠的 条评论
为什么被折叠?



