十个python高级代码片段(Ⅲ)

1. 上下文管理器 for 锁

import threading

lock = threading.Lock()

def thread_safe_increment(counter):
    with lock:
        counter[0] += 1

counter = [0]
threads = [threading.Thread(target=thread_safe_increment, args=(counter,)) for _ in range(100)]

for thread in threads:
    thread.start()

for thread in threads:
    thread.join()

print(counter[0])  # 输出: 100

说明: 使用上下文管理器管理锁,确保在多线程环境中对共享资源的操作是线程安全的。

2. 类型提示

from typing import List, Tuple

def process_data(data: List[Tuple[int, str]]) -> List[str]:
    return [f"{num}: {text}" for num, text in data]

sample_data = [(1, "apple"), (2, "banana")]
print(process_data(sample_data))  # 输出: ['1: apple', '2: banana']

说明: 类型提示(Type Hints)用于指定函数参数和返回值的类型,增强代码可读性和工具支持。

3. 反射

class MyClass:
    def method(self):
        pass

obj = MyClass()
method = getattr(obj, 'method')
method()  # 动态调用方法

说明: 反射允许在运行时检查和操作对象的属性和方法,这对于动态创建和调用方法非常有用。

4. 数据生成器

import random

def random_numbers(size: int):
    for _ in range(size):
        yield random.randint(1, 100)

numbers = random_numbers(5)
print(list(numbers))  # 输出: 随机的五个数字

说明: 生成器提供一种迭代大数据集的方式,避免将所有数据一次性加载到内存中。

5. 分派函数

from functools import singledispatch

@singledispatch
def process(arg):
    print(f"Default processing for {arg}")

@process.register
def _(arg: int):
    print(f"Processing integer: {arg}")

@process.register
def _(arg: str):
    print(f"Processing string: {arg}")

process(10)   # 输出: Processing integer: 10
process("hi") # 输出: Processing string: hi

说明: singledispatch实现了基于函数参数类型的单分派,可以简化代码逻辑,替代大量的if-elif语句。

6. 复数的使用

complex_num1 = complex(2, 3)
complex_num2 = complex(1, -4)
result = complex_num1 + complex_num2

print(result)  # 输出: (3-1j)
print(result.real)  # 输出: 3.0
print(result.imag)  # 输出: -1.0

说明: Python内置对复数的支持,提供了丰富的数学操作和属性访问。

7. 动态导入模块

module_name = 'math'
math_module = __import__(module_name)

print(math_module.sqrt(16))  # 输出: 4.0

说明: 动态导入模块可以根据运行时的条件决定导入哪些模块,适用于需要动态加载插件或扩展的场景。

8. 组合生成器

from itertools import product

colors = ['red', 'green', 'blue']
sizes = ['S', 'M', 'L']

for combination in product(colors, sizes):
    print(combination)
# 输出: ('red', 'S'), ('red', 'M'), ('red', 'L'), ...

说明: 使用itertools.product可以生成两个或多个列表的笛卡尔积,非常适合在需要生成所有可能组合的场景下使用。

9. 动态创建类

def class_factory(class_name):
    class Base:
        def __init__(self):
            self.name = class_name
    return Base

DynamicClass = class_factory("DynamicClass")
instance = DynamicClass()
print(instance.name)  # 输出: DynamicClass

说明: 动态创建类允许根据运行时条件生成类,提供高度的灵活性和扩展性。

10. 序列解包

data = [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
for name, age in data:
    print(f"{name} is {age} years old")
# 输出:
# Alice is 25 years old
# Bob is 30 years old
# Charlie is 35 years old

说明: 序列解包用于将序列中的元素直接分配给多个变量,这使得代码更加简洁和清晰。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值