当前位置: 首页 > news >正文

10-高级主题

第10节 高级主题

在这一节中,我们将探讨一些 Python 中的高级主题,包括装饰器、生成器、上下文管理器、元类以及常用的设计模式。这些高级特性能够帮助你编写更强大、更灵活的代码。

10.1 装饰器

装饰器是一种特殊类型的函数,可以修改其他函数的功能或行为,而无需改变原函数的代码。装饰器通常用于日志记录、性能测试、事务处理等场景。

基本语法:

@decorator
def function_to_decorate():
    pass

示例:

  1. 定义一个简单的装饰器:

    def my_decorator(func):
        def wrapper():
            print("Something is happening before the function is called.")
            func()
            print("Something is happening after the function is called.")
        return wrapper

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

    say_hello()

    输出:

    Something is happening before the function is called.
    Hello!
    Something is happening after the function is called.
  2. 带参数的装饰器:

    def repeat(num_times):
        def decorator(func):
            def wrapper(*args, **kwargs):
                for _ in range(num_times):
                    result = func(*args, **kwargs)
                return result
            return wrapper
        return decorator

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

    greet("Alice")

    输出:

    Hello, Alice!
    Hello, Alice!
    Hello, Alice!
10.2 生成器

生成器是一种特殊的迭代器,可以生成一系列值,但不占用大量内存。生成器使用 yield 关键字来生成值。

基本语法:

def generator_function():
    yield value

示例:

  1. 定义一个简单的生成器:

    def count_up_to(n):
        count = 1
        while count <= n:
            yield count
            count += 1

    counter = count_up_to(5)
    for num in counter:
        print(num)

    输出:

    1
    2
    3
    4
    5
  2. 生成器表达式:

    even_numbers = (x for x in range(10if x % 2 == 0)
    for num in even_numbers:
        print(num)

    输出:

    0
    2
    4
    6
    8
10.3 上下文管理器

上下文管理器用于管理资源的生命周期,确保资源在使用后正确释放。通常使用 with 语句来实现上下文管理。

基本语法:

with context_manager as resource:
    # 使用资源

示例:

  1. 定义一个简单的上下文管理器:

    class ManagedFile:
        def __init__(self, filename):
            self.filename = filename

        def __enter__(self):
            self.file = open(self.filename, 'r')
            return self.file

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

    with ManagedFile('example.txt'as file:
        content = file.read()
        print(content)
  2. 使用 contextlib 模块中的 contextmanager 装饰器:

    from contextlib import contextmanager

    @contextmanager
    def managed_file(filename):
        try:
            file = open(filename, 'r')
            yield file
        finally:
            file.close()

    with managed_file('example.txt'as file:
        content = file.read()
        print(content)
10.4 元类

元类是创建类的类。元类允许你在类创建时动态地修改类的行为。

基本语法:

class Meta(type):
    def __new__(cls, name, bases, dct):
        # 修改类的行为
        return super().__new__(cls, name, bases, dct)

class MyClass(metaclass=Meta):
    pass

示例:

  1. 定义一个简单的元类:

    class UpperCaseMeta(type):
        def __new__(cls, name, bases, dct):
            upper_case_dct = {}
            for key, value in dct.items():
                if callable(value):
                    upper_case_dct[key.upper()] = value
                else:
                    upper_case_dct[key] = value
            return super().__new__(cls, name, bases, upper_case_dct)

    class MyClass(metaclass=UpperCaseMeta):
        def greet(self):
            print("Hello, World!")

    obj = MyClass()
    obj.GREET()  # 注意方法名变为大写

    输出:

    Hello, World!
10.5 常用设计模式

设计模式是解决常见问题的通用模板。以下是一些常用的 Python 设计模式:

  • 单例模式:确保一个类只有一个实例,并提供一个全局访问点。
  • 工厂模式:定义一个创建对象的接口,但让子类决定实例化哪个类。
  • 观察者模式:定义对象间的一对多依赖关系,当一个对象的状态改变时,所有依赖于它的对象都会得到通知并自动更新。

示例:

  1. 单例模式:

    class Singleton:
        _instance = None

        def __new__(cls, *args, **kwargs):
            if not cls._instance:
                cls._instance = super().__new__(cls, *args, **kwargs)
            return cls._instance

    s1 = Singleton()
    s2 = Singleton()

    print(s1 is s2)  # 输出: True
  2. 工厂模式:

    class Dog:
        def speak(self):
            return "Woof!"

    class Cat:
        def speak(self):
            return "Meow!"

    class AnimalFactory:
        def get_animal(self, animal_type):
            if animal_type == "dog":
                return Dog()
            elif animal_type == "cat":
                return Cat()
            else:
                raise ValueError("Invalid animal type")

    factory = AnimalFactory()
    dog = factory.get_animal("dog")
    cat = factory.get_animal("cat")

    print(dog.speak())  # 输出: Woof!
    print(cat.speak())  # 输出: Meow!
  3. 观察者模式:

    class Subject:
        def __init__(self):
            self._observers = []

        def attach(self, observer):
            self._observers.append(observer)

        def detach(self, observer):
            self._observers.remove(observer)

        def notify(self, message):
            for observer in self._observers:
                observer.update(message)

    class Observer:
        def update(self, message):
            print(f"Received message: {message}")

    subject = Subject()
    observer1 = Observer()
    observer2 = Observer()

    subject.attach(observer1)
    subject.attach(observer2)

    subject.notify("Hello, Observers!")  # 输出: Received message: Hello, Observers! (两次)

小结

通过本节的学习,你应该已经掌握了 Python 中的一些高级主题,包括装饰器、生成器、上下文管理器、元类以及常用的设计模式。这些高级特性能够帮助你编写更强大、更灵活的代码,提升程序的性能和可维护性。下一节我们将继续学习 Python 中的网络编程。

本文由 mdnice 多平台发布

http://www.lryc.cn/news/497733.html

相关文章:

  • harbor常见问题及解决方法分享
  • 行列式与线性方程组解的关系
  • 四、自然语言处理_02RNN基础知识笔记
  • Spring 容器管理 Bean
  • SpringBoot开发——Spring Boot3.4 强大的结构化日志记录
  • 信号和槽思维脑图+相关练习
  • Unity Feel插件快速入门
  • 数据链路层(四)---PPP协议的工作状态
  • 【C++】入门【六】
  • UE5 C++ 不规则按钮识别,复选框不规则识别 UPIrregularWidgets
  • Elasticsearch Serverless 现已正式发布
  • 如何使用apache部署若依前后端分离项目
  • openEuler安装UKUI桌面
  • 深入理解Oracle DB的锁和闩
  • jenkins+github+springboot自动部署
  • HTML5系列(10)-- 地理位置服务指南
  • 【MySQL 进阶之路】SQL 优化
  • Web3的技术栈详解:解读区块链、智能合约与分布式存储
  • [在线实验]-在docker中运行clickhouse
  • Rust常用命令总结
  • Ant-Design X,AI组件库
  • Matplotlib 内置的170种颜色映射(colormap)
  • 在linux虚拟机安装VMware tools
  • 初识EasyFramework
  • OpenStack-Glance组件
  • SPC三种判定准则的算法
  • 20241129解决在Ubuntu20.04下编译中科创达的CM6125的Android10出现找不到库文件libncurses.so.5的问题
  • Mybatis @MapKey注解实现List转Map
  • vue中使用socket.io统计在线用户
  • zotero中pdf-translate插件和其他插件的安装