Python的进阶演示

91 阅读2分钟

为了展示 Python 进阶的一些常见概念,我将通过代码演示几个典型的进阶技术,包括 面向对象编程(OOP)装饰器生成器上下文管理器异步编程 等内容。

1. 面向对象编程(OOP)演示

python
复制编辑
class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        raise NotImplementedError("Subclass must implement abstract method")

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

# 使用多态
animals = [Dog("Buddy"), Cat("Whiskers")]

for animal in animals:
    print(animal.speak())

解释:

  • Animal 是一个基类,DogCat 是它的子类。
  • 子类实现了 speak 方法,并且通过多态,可以根据不同对象返回不同的结果。

2. 装饰器(Decorators)演示

python
复制编辑
# 定义一个简单的装饰器
def decorator(func):
    def wrapper():
        print("Before function execution")
        func()
        print("After function execution")
    return wrapper

# 使用装饰器
@decorator
def say_hello():
    print("Hello!")

say_hello()

解释:

  • decorator 是一个装饰器函数,它接受一个函数 func 作为参数,返回一个新的函数 wrapper,该函数在调用原函数前后执行额外的操作。
  • @decorator 是装饰器的语法糖,等价于 say_hello = decorator(say_hello)

3. 生成器(Generators)演示

python
复制编辑
# 定义一个简单的生成器函数
def count_up_to(max):
    count = 1
    while count <= max:
        yield count
        count += 1

# 使用生成器
for num in count_up_to(5):
    print(num)

解释:

  • yield 关键字用于返回一个生成器对象,生成器可以在每次迭代时暂停并返回值,直到下次迭代时继续执行。
  • 生成器通常用于处理大型数据集或流式数据,因为它们不会一次性占用大量内存。

4. 上下文管理器(Context Managers)演示

python
复制编辑
# 自定义上下文管理器
class FileOpener:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode

    def __enter__(self):
        print("Opening file...")
        self.file = open(self.filename, self.mode)
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Closing file...")
        if self.file:
            self.file.close()

# 使用上下文管理器
with FileOpener("test.txt", "w") as f:
    f.write("Hello, world!")

解释:

  • __enter____exit__ 方法使得 FileOpener 成为一个上下文管理器。
  • with 语句会自动调用 __enter____exit__,确保文件在操作完后正确关闭,即使出现异常也能正确释放资源。

5. 异步编程(Asyncio)演示

python
复制编辑
import asyncio

async def fetch_data():
    print("Fetching data...")
    await asyncio.sleep(2)
    print("Data fetched!")

async def main():
    # 异步执行多个任务
    task1 = asyncio.create_task(fetch_data())
    task2 = asyncio.create_task(fetch_data())

    # 等待所有任务完成
    await task1
    await task2

# 运行事件循环
asyncio.run(main())

解释:

  • 使用 asyncawait 关键字定义异步函数,await 会暂停当前函数的执行,直到异步操作完成。
  • asyncio 库提供了异步任务调度和事件循环的功能,使得可以并发处理 I/O 密集型任务。 这些进阶技术将帮助你编写更加优雅、高效和可维护的 Python 代码,适用于更复杂的开发场景 海尔运营级源码haierym.com