Python 函数与装饰器
Python 函数定义、参数系统与装饰器机制。
#type / concept
#status / growing
#resource / python
#tech / lang / python
[!info] related notes
- 所属 MOC: python-moc
- 前置概念: python数据类型与数据结构
- 并列概念: python类与面向对象, python异步编程
- 关系笔记: python
Python 函数与装饰器
函数是 Python 中的一等公民,装饰器是修改函数行为的语法糖。
核心机制
函数定义
def greet(name: str, greeting: str = "Hello") -> str:
return f"{greeting}, {name}!"
# 可变参数
def sum_all(*args):
return sum(args)
# 关键字参数
def config(**kwargs):
return kwargs
闭包
def counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
c = counter()
c() # 1
c() # 2
装饰器
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.time() - start:.2f}s")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
带参数的装饰器
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(times=3)
def say_hello():
print("Hello!")
常见误解或边界
- 装饰器顺序: 多个装饰器从下往上应用,从上往下执行
- functools.wraps: 装饰器会丢失原函数元信息,需用
@functools.wraps保留 - 闭包变量: 闭包捕获的是变量引用,不是值