GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.runoob.com — Python 装饰器 | 菜鸟教程
Python 3 教程
Python3 教程
Python3 简介
Python3 环境搭建
Python3 Pycharm
Python3 VScode
Python3 基础语法
Python3 基本数据类型
Python3 数据类型转换
Python3 解释器
Python3 注释
Python3 运算符
Python3 数字(Number)
Python3 字符串
Python3 列表
Python3 元组
Python3 字典
Python3 集合
Python3 条件控制
Python3 循环语句
Python3 编程第一步
Python3 推导式
Python3 迭代器与生成器
Python3 with
Python3 函数
Python3 lambda
Python3 装饰器
Python3 数据结构
Python3 模块
Python __name__
Python3 输入和输出
Python3 File
Python3 OS
Python3 错误和异常
Python3 面向对象
Python3 命名空间/作用域
Python 虚拟环境的创建
Python 类型注解
Python3 标准库概览
Python3 实例
Python 测验
Python3 高级教程Python3 正则表达式 Python3 CGI编程 Python3 MySQL(mysql-connector) Python3 MySQL(PyMySQL) Python3 网络编程 Python3 SMTP发送邮件 Python3 多线程 Python3 XML 解析 Python3 JSON Python3 日期和时间 Python3 内置函数 Python3 MongoDB Python3 urllib Python uWSGI 安装配置 Python3 pip Python3 operator Python math Python requests Python random Python OpenAI Python 有用的资源 Python AI 绘画 Python statistics Python hashlib Python 量化 Python pyecharts Python selenium 库 Python 爬虫 Python Scrapy 库 Python Markdown Python sys 模块 Python Pickle 模块 Python subprocess 模块 Python queue 模块 Python StringIO 模块 Python logging 模块 Python datetime 模块 Python re 模块 Python csv 模块 Python threading 模块 Python asyncio 模块 Python PyQtPython 装饰器装饰器(decorator)是 Python 中的一种高级功能,用于在不修改原函数代码的前提下,动态扩展函数或类的功能。 本质上,装饰器是一个函数:它接收一个函数作为参数,并返回一个新的函数(通常是对原函数的增强版本)。
装饰器通过 @decorator_name 语法应用在函数或方法定义之前。 Python 还提供了一些内置装饰器,例如 @staticmethod 和 @classmethod。 常见应用场景:
基本语法装饰器的核心思想是:用一个函数"包装"另一个函数。 语法
def decorator_function(original_function):
def wrapper(*args, **kwargs): # 调用前 print("执行前") result = original_function(*args, **kwargs) # 调用后 print("执行后") return result return wrapper @decorator_function def target_function(): print("原函数执行") 解析:
等价写法: target_function = decorator_function(target_function)
👉 调用 使用装饰器装饰器通过 @ 语法糖应用在函数定义前: @time_logger
def target_function():
pass
等价于: def target_function():
pass
target_function = time_logger(target_function)
这种机制使我们可以在不修改原函数的情况下,统一添加功能(如日志、权限等)。 实例:打印日志
def my_decorator(func):
def wrapper(): print("函数执行前") func() print("函数执行后") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello() 输出: 函数执行前 Hello! 函数执行后
带参数的装饰器
如果原函数有参数,需要在 实例
def my_decorator(func):
def wrapper(*args, **kwargs): print("执行前") func(*args, **kwargs) print("执行后") return wrapper @my_decorator def greet(name): print(f"Hello, {name}!") greet("Alice") 输出: 执行前 Hello, Alice! 执行后
说明:使用 带参数的装饰器(进阶)
def repeat(num_times):
def decorator(func): def wrapper(*args, **kwargs): for _ in range(num_times): func(*args, **kwargs) return wrapper return decorator @repeat(3) def say_hello(): print("Hello!") say_hello() 说明:这是"装饰器工厂",外层函数用于接收参数。 Hello! Hello! Hello!
类装饰器除了函数,装饰器也可以作用于类。 类装饰器接收一个类,并返回修改后的类或包装类。
函数形式的类装饰器实例
def log_class(cls):
class Wrapper: def __init__(self, *args, **kwargs): self.wrapped = cls(*args, **kwargs) def __getattr__(self, name): return getattr(self.wrapped, name) def display(self): print("调用前") self.wrapped.display() print("调用后") return Wrapper @log_class class MyClass: def display(self): print("原方法") obj = MyClass() obj.display() 调用前 原方法 调用后 类形式的类装饰器实例:单例模式
class SingletonDecorator:
def __init__(self, cls): self.cls = cls self.instance = None def __call__(self, *args, **kwargs): if self.instance is None: self.instance = self.cls(*args, **kwargs) return self.instance @SingletonDecorator class Database: def __init__(self): print("初始化") db1 = Database() db2 = Database() print(db1 is db2) 初始化 True 内置装饰器常用内置装饰器:
实例
class MyClass:
@staticmethod def static_method(): print("静态方法") @classmethod def class_method(cls): print(cls.__name__) @property def name(self): return self._name @name.setter def name(self, value): self._name = value 多个装饰器的堆叠多个装饰器在定义阶段从下到上依次包裹函数,调用阶段从上到下依次执行: 实例
def decorator1(func):
def wrapper(): print("Decorator 1") func() return wrapper def decorator2(func): def wrapper(): print("Decorator 2") func() return wrapper @decorator1 @decorator2 def say_hello(): print("Hello!") say_hello() 最终输出: Decorator 1 Decorator 2 Hello! 核心总结装饰器 = 函数包装函数 + 不修改原代码扩展功能
AI 思考中...
点我分享笔记取消
分类导航
Advertisement
|
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |