python什么是装饰器

1 python什么是装饰器

python装饰器本身是一个函数,它在不修改原函数或类的情况下,接受一个原函数或类作为参数,为原函数或类添加新逻辑,然后返回函数或类。是管理函数和类的一种方式。

此处原函数或类,为被修饰的函数或类,也称为主体函数或主体类。

函数装饰器

定义主体函数时进行名称重绑定,提供一个逻辑层来管理函数和方法,或随后对它们的调用。

在主体函数上一行,用@标注装饰器函数,自动调用装饰器函数,且将其返回值赋给主体函数。

用法

python 复制代码
@f_decorator
def testfunc():pass

描述

@f_decorator:模块导入时,自动调用装饰器函数f_decorator;

testfunc:将装饰器函数返回值赋给被装饰函数testfunc变量;

示例

常规调用

python 复制代码
>>> def f_decorator(func):
    print('装饰器函数被调用')
    return func

>>> def testfunc():
    print('testfunc主体函数被调用')

    
>>> fd=f_decorator(testfunc)
装饰器函数被调用
>>> fd()
testfunc主体函数被调用

函数装饰器调用

python 复制代码
# ls.py
def f_decorator(func):
    print('装饰器函数被调用')
    def f_wrap():
        print('f_wrap装饰器返回函数被调用')
        func()
    return f_wrap
# @f_decorator 自动调用装饰器函数
# 将装饰器函数返回值赋给被装饰函数
@f_decorator
def testfunc():
    print('testfunc主体函数被调用')
print('调用装饰器返回的函数'.center(50,'='))
testfunc()

cmd执行结果

python 复制代码
E:\documents\F盘>d:\python39\python.exe ls.py
装饰器函数被调用
====================调用装饰器返回的函数====================
f_wrap装饰器返回函数被调用
testfunc主体函数被调用

类装饰器

定义主体类时进行名称重绑定,提供一个逻辑层来管理类,或随后调用它们所创建的实例。

在主体类上一行,用@标注装饰器函数,自动调用装饰器函数,且将其返回值赋给主体类。

用法

python 复制代码
@c_decorator
class TestCls:pass

描述

@c_decorator:模块导入时,自动调用装饰器函数c_decorator;

TestCls:将装饰器函数返回值赋给被装饰类TestCls变量;

示例

常规调用

python 复制代码
>>> def c_decorator(cls):
    print('装饰器函数被调用')
    def c_wrap():
        print('c_wrap装饰器返回包装函数被调用')
        cls()
    return c_wrap

>>> class TestCls:
    def __init__(self):
        print('TestCls构造函数被调用')

        
>>> cd=c_decorator(TestCls)
装饰器函数被调用
>>> cd()
c_wrap装饰器返回包装函数被调用
TestCls构造函数被调用

函数装饰器调用

python 复制代码
# ls.py
def c_decorator(cls):
    print('装饰器函数被调用')
    def c_wrap():
        print('c_wrap装饰器返回包装函数被调用')
        cls()
    return c_wrap

@c_decorator
class TestCls:
    def __init__(self):
        print('TestCls构造函数被调用')

print('调用装饰器返回的函数'.center(50,'='))
TestCls()

cmd执行结果

python 复制代码
E:\documents\F盘>d:\python39\python.exe ls.py
装饰器函数被调用
====================调用装饰器返回的函数====================
c_wrap装饰器返回包装函数被调用
TestCls构造函数被调用
相关推荐
YJlio6 小时前
1.7 通过 Sysinternals Live 在线运行工具:不下载也能用的“云端工具箱”
c语言·网络·python·数码相机·ios·django·iphone
l1t6 小时前
在wsl的python 3.14.3容器中使用databend包
开发语言·数据库·python·databend
山塘小鱼儿7 小时前
本地Ollama+Agent+LangGraph+LangSmith运行
python·langchain·ollama·langgraph·langsimth
码说AI7 小时前
python快速绘制走势图对比曲线
开发语言·python
wait_luky8 小时前
python作业3
开发语言·python
Python大数据分析@9 小时前
tkinter可以做出多复杂的界面?
python·microsoft
大黄说说9 小时前
新手选语言不再纠结:Java、Python、Go、JavaScript 四大热门语言全景对比与学习路线建议
java·python·golang
小小张说故事9 小时前
SQLAlchemy 技术入门指南
后端·python
我是章汕呐10 小时前
拆解Libvio.link爬虫:从动态页面到反爬对抗的实战解析
爬虫·python