跳转至

代码片段->装饰器

异常处理装饰器

异常处理装饰器
def log_info_and_exception(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            print(f"❌ ❌ ❌ in {func.__name__}: {e} ❌ ❌ ❌ ")
    return wrapper

# 使用装饰器
@log_info_and_exception
def example_function():
    result = 1 / 2
    print(f"Result: {result}")

重试装饰器

重试装饰器
import time

def retry_on_exception(max_retries=3, wait_seconds=1):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for attempt in range(1, max_retries + 1):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    print(f"第{attempt}次尝试失败| {func.__name__} ==》{e}")
                    if attempt < max_retries:
                        print(f" {wait_seconds} 秒后重试 ...")
                        time.sleep(wait_seconds)
                    else:
                        raise e
            print(f"全部执行失败!!!")
        return wrapper
    return decorator

# 使用装饰器
@retry_on_exception(max_retries=3, wait_seconds=2)
def example_function(x, y):
    result = x / y
    print(f"Result: {result}")

# 测试
example_function(10, 0)

Lambda函数

当使用Lambda函数时,注释和高级使用方法可以使代码更易读和功能更丰富。下面是对Lambda函数在map、filter、sorted、reduce等内置函数的详细注释和高级用法:

1. 使用Lambda函数和sorted按照元组中的第二个元素排序:

1
2
3
4
5
6
7
# 列表中的元组,按照第二个元素进行排序
a = [('b', 3), ('a', 2), ('d', 4), ('c', 1)]

# 高级用法:按照元组中的第二个元素进行排序
sorted_a = sorted(a, key=lambda x: x[1])
# 输出: [('c', 1), ('a', 2), ('b', 3), ('d', 4)]
print(sorted_a)

2. 使用Lambda函数和map将两个列表对应位置的元素相乘:

1
2
3
4
5
6
# 两个列表对应位置的元素相乘
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list(map(lambda x, y: x * y, list1, list2))
# 输出: [4, 10, 18]
print(result)

3. 使用Lambda函数和filter过滤出长度大于等于3的字符串:

1
2
3
4
5
# 过滤出长度大于等于3的字符串
words = ['apple', 'banana', 'kiwi', 'orange']
filtered_words = list(filter(lambda x: len(x) >= 3, words))
# 输出: ['apple', 'banana', 'kiwi', 'orange']
print(filtered_words)

4. 使用Lambda函数和reduce计算列表中所有元素的累积:

1
2
3
4
5
6
7
from functools import reduce

# 计算列表中所有元素的累积
numbers = [1, 2, 3, 4, 5]
product_result = reduce(lambda x, y: x * y, numbers)
# 输出: 120
print(product_result)