python高级特性

Posted by WK on 2025-04-10
Estimated Reading Time 5 Minutes
Words 1.1k In Total
Viewed Times

Python 的高级特性

Python 的高级特性使其在开发过程中更加灵活和高效。这些特性包括但不限于生成器、装饰器、上下文管理器、元编程、多线程与多进程等。以下是 Python 高级特性的详细介绍:


一、生成器(Generators)

生成器是一种特殊的迭代器,允许按需生成值,而不是一次性生成所有值。它通过 yield 关键字实现。

1. 生成器函数

  • 使用 yield 返回值。
  • 每次调用 next() 时,生成器会从上次暂停的地方继续执行。
    1
    2
    3
    4
    5
    6
    7
    def generate_numbers():
    for i in range(5):
    yield i

    gen = generate_numbers()
    print(next(gen)) # 输出 0
    print(next(gen)) # 输出 1

2. 生成器表达式

  • 类似列表推导式,但使用圆括号 () 而不是方括号 [
    1
    2
    3
    squares = (x**2 for x in range(5))
    for square in squares:
    print(square)

3. 优点

  • 节省内存:生成器只在需要时生成值,适合处理大数据集。
  • 简化代码:避免显式实现迭代器协议。

二、装饰器(Decorators)

装饰器是一种用于修改或增强函数或方法行为的工具。它们本质上是一个高阶函数,接受一个函数作为输入并返回一个新的函数。

1. 基本语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper

@my_decorator
def say_hello():
print("Hello!")

say_hello()
# 输出:
# Before function call
# Hello!
# After function call

2. 带参数的装饰器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator

@repeat(3)
def greet(name):
print(f"Hello, {name}!")

greet("Alice")
# 输出:
# Hello, Alice!
# Hello, Alice!
# Hello, Alice!

3. 内置装饰器

  • @staticmethod:定义静态方法。
  • @classmethod:定义类方法。
  • @property:将方法转换为属性。

三、上下文管理器(Context Managers)

上下文管理器用于管理资源(如文件、数据库连接)的分配和释放,通常与 with 语句配合使用。

1. 基本用法

1
2
3
with open("example.txt", "r") as file:
content = file.read()
# 文件会在退出 `with` 块后自动关闭

2. 自定义上下文管理器

  • 实现 __enter____exit__ 方法。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    class MyContextManager:
    def __enter__(self):
    print("Entering context")
    return self

    def __exit__(self, exc_type, exc_val, exc_tb):
    print("Exiting context")

    with MyContextManager() as cm:
    print("Inside context")

3. 使用 contextlib

  • 使用 @contextlib.contextmanager 装饰器简化上下文管理器的实现。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    from contextlib import contextmanager

    @contextmanager
    def my_context():
    print("Entering context")
    try:
    yield
    finally:
    print("Exiting context")

    with my_context():
    print("Inside context")

四、元编程(Metaprogramming)

元编程是指编写能够操作其他程序(或自身)的代码的能力。Python 提供了强大的元编程工具,如动态创建类、修改类或函数的行为。

1. 动态创建类

  • 使用 type 动态创建类。
    1
    2
    3
    MyClass = type("MyClass", (object,), {"x": 10})
    obj = MyClass()
    print(obj.x) # 输出 10

2. 描述符(Descriptors)

  • 描述符是实现了特定协议的类(__get__, __set__, __delete__)。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class Descriptor:
    def __get__(self, instance, owner):
    return instance._value

    def __set__(self, instance, value):
    instance._value = value

    class MyClass:
    attr = Descriptor()

    obj = MyClass()
    obj.attr = 42
    print(obj.attr) # 输出 42

3. 元类(Metaclasses)

  • 元类用于控制类的创建过程。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    class MyMeta(type):
    def __new__(cls, name, bases, dct):
    print(f"Creating class {name}")
    return super().__new__(cls, name, bases, dct)

    class MyClass(metaclass=MyMeta):
    pass

    # 输出:Creating class MyClass

五、多线程与多进程

Python 支持并发编程,可以通过多线程或多进程来提高程序性能。

1. 多线程(Multithreading)

  • 使用 threading 模块。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    import threading

    def worker():
    print(f"Thread {threading.current_thread().name} is running")

    threads = []
    for i in range(5):
    t = threading.Thread(target=worker)
    threads.append(t)
    t.start()

    for t in threads:
    t.join()

2. 多进程(Multiprocessing)

  • 使用 multiprocessing 模块,适合 CPU 密集型任务。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    from multiprocessing import Process

    def worker():
    print(f"Process {os.getpid()} is running")

    processes = []
    for _ in range(5):
    p = Process(target=worker)
    processes.append(p)
    p.start()

    for p in processes:
    p.join()

3. 异步编程(Asyncio)

  • 使用 asyncio 模块,适合 I/O 密集型任务。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import asyncio

    async def task():
    print("Task started")
    await asyncio.sleep(1)
    print("Task finished")

    async def main():
    await asyncio.gather(task(), task(), task())

    asyncio.run(main())

六、数据序列化与反序列化

1. pickle

  • 用于序列化和反序列化 Python 对象。
    1
    2
    3
    4
    5
    import pickle

    data = {"name": "Alice", "age": 25}
    serialized = pickle.dumps(data)
    deserialized = pickle.loads(serialized)

2. json

  • 用于处理 JSON 数据。
    1
    2
    3
    4
    5
    import json

    data = {"name": "Alice", "age": 25}
    json_str = json.dumps(data)
    parsed_data = json.loads(json_str)

七、其他高级特性

1. 命名空间与作用域:

  • globals()locals() 查看全局和局部变量。

2. 动态导入模块:

  • 使用 importlib 动态加载模块。

3. 弱引用(Weak References):

  • 使用 weakref 模块管理对象的弱引用。

4. 协程(Coroutines):

  • 使用 asyncawait 实现协程。


If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !