Python 函数与装饰器

Python 函数定义、参数系统与装饰器机制。

#type / concept #status / growing #resource / python #tech / lang / python

[!info] related notes

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!")

常见误解或边界

  1. 装饰器顺序: 多个装饰器从下往上应用,从上往下执行
  2. functools.wraps: 装饰器会丢失原函数元信息,需用 @functools.wraps 保留
  3. 闭包变量: 闭包捕获的是变量引用,不是值
创建于 2026/3/24 更新于 2026/5/27