← 返回首页
🐍

高级函数

📂 python ⏱ 2 min 351 words

Lambda匿名函数

Lambda是一种简洁的函数定义方式,适用于简单的单行函数。

# 普通函数
def add(x, y):
    return x + y

# Lambda表达式
add_lambda = lambda x, y: x + y

print(add(3, 5))        # 输出: 8
print(add_lambda(3, 5))  # 输出: 8

# Lambda作为参数
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)  # 输出: [1, 4, 9, 16, 25]

闭包

闭包是记住定义时环境变量的函数,它在函数式编程中非常重要。

def create_counter(start=0):
    count = [start]
    def counter():
        count[0] += 1
        return count[0]
    return counter

# 创建闭包
counter1 = create_counter(10)
counter2 = create_counter(20)

print(counter1())  # 输出: 11
print(counter1())  # 输出: 12
print(counter2())  # 输出: 21

# 闭包用于配置
def create_validator(min_val, max_val):
    def validator(value):
        return min_val <= value <= max_val
    return validator

age_validator = create_validator(0, 150)
print(age_validator(25))   # 输出: True
print(age_validator(200))  # 输出: False

装饰器基础

装饰器是一种修改函数行为的高级技术,它不改变原函数的代码。

import time

# 简单的计时装饰器
def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} 执行时间: {end - start:.4f}秒")
        return result
    return wrapper

# 使用装饰器
@timer
def slow_function():
    time.sleep(1)
    return "完成"

result = slow_function()
print(result)

带参数的装饰器

装饰器本身也可以接受参数,这需要三层函数嵌套。

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(3)
def greet(name):
    print(f"你好,{name}!")

greet("张三")
# 输出三次: 你好,张三!

类装饰器

除了函数装饰器,Python还支持类装饰器。

class Timer:
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        start = time.time()
        result = self.func(*args, **kwargs)
        end = time.time()
        print(f"{self.func.__name__} 执行时间: {end - start:.4f}秒")
        return result

@Timer
def another_slow_function():
    time.sleep(0.5)
    return "完成"

result = another_slow_function()

functools.wraps

使用装饰器时,原函数的元信息(如函数名、文档字符串)会丢失,functools.wraps可以解决这个问题。

from functools import wraps

def my_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        """包装器函数的文档字符串"""
        return func(*args, **kwargs)
    return wrapper

@my_decorator
def example():
    """这是示例函数的文档字符串"""
    pass

print(example.__name__)  # 输出: example
print(example.__doc__)   # 输出: 这是示例函数的文档字符串

偏函数

偏函数通过固定函数的部分参数来创建新函数。

from functools import partial

# 创建偏函数
def power(base, exponent):
    return base ** exponent

square = partial(power, exponent=2)
cube = partial(power, exponent=3)

print(square(5))  # 输出: 25
print(cube(5))    # 输出: 125

# 实际应用:配置默认参数
def connect(host, port, protocol='http'):
    return f"连接到 {protocol}://{host}:{port}"

# 创建特定协议的连接函数
http_connect = partial(connect, protocol='https')
print(http_connect('example.com', 8080))
# 输出: 连接到 https://example.com:8080

函数组合

将多个函数组合成一个新函数,实现更复杂的操作。

def compose(*functions):
    def composed(x):
        result = x
        for func in reversed(functions):
            result = func(result)
        return result
    return composed

def double(x):
    return x * 2

def add_one(x):
    return x + 1

def square(x):
    return x ** 2

# 组合函数
transform = compose(double, add_one, square)
print(transform(3))  # 输出: 50 (先平方得9,加1得10,乘2得20)

# 等价于
print(double(add_one(square(3))))  # 输出: 50

最佳实践

掌握这些高级函数特性,能让你的Python代码更加优雅和高效。