Python:decorator装饰器的使用示例

简介: Python:decorator装饰器的使用示例

定义一个装饰器

def decorator(func):
    def wrapper(*arg, **kwargs):
        print("before")
        ret = func(*arg, **kwargs)
        print("after")
        return ret
    return wrapper

使用示例


# -*- coding: utf-8 -*-
# 作用于普通方法
@decorator
def foo(name):
    print('my name is:', name)
class Foo(object):
    # 作用于实例方法
    @decorator
    def foo(self, name):
        print('my name is:', name)
    # 作用于类方法
    @classmethod
    @decorator
    def class_foo(cls, name):
        print('my name is:', name)
    # 作用于静态方法
    @staticmethod
    @decorator
    def static_foo(name):
        print('my name is:', name)
if __name__ == '__main__':
    foo('Tom')
    Foo().foo('Tom')
    Foo.class_foo('Tom')
    Foo.static_foo('Tom')
"""
4中方式都可以正常执行,输入如下
before
my name is: Tom
after
"""

如果把装饰器函数参数修改了

def decorator(func):
    def wrapper(name):
        print("before")
        # ret = func(*arg, **kwargs)
        # 取消原来的不定参数,写为固定参数
        ret = func(name)
        print("after")
        return ret
    return wrapper

执行结果

# 普通函数可以正常执行
foo('Tom')
# 静态方法可以正常执行
Foo.static_foo('Tom')
# 实例方法报错
Foo().foo('Tom')
# TypeError: wrapper() takes 1 positional argument but 2 were given
# 类方法报错
Foo.class_foo('Tom')
# TypeError: wrapper() takes 1 positional argument but 2 were given

综上,一般情况下需要写成不定参数的形式,兼容性更强

相关文章
|
20天前
|
测试技术 Python
Python装饰器:为你的代码施展“魔法”
Python装饰器:为你的代码施展“魔法”
200 100
|
28天前
|
设计模式 缓存 监控
Python装饰器:优雅增强函数功能
Python装饰器:优雅增强函数功能
238 101
|
20天前
|
缓存 Python
Python装饰器:为你的代码施展“魔法
Python装饰器:为你的代码施展“魔法
131 88
|
1月前
|
缓存 测试技术 Python
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
171 99
|
1月前
|
存储 缓存 测试技术
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
151 98
|
1月前
|
缓存 Python
Python中的装饰器:优雅地增强函数功能
Python中的装饰器:优雅地增强函数功能
|
1月前
|
存储 缓存 测试技术
理解Python装饰器:简化代码的强大工具
理解Python装饰器:简化代码的强大工具
|
28天前
|
缓存 测试技术 Python
解锁Python超能力:深入理解装饰器
解锁Python超能力:深入理解装饰器
79 2
|
1月前
|
设计模式 缓存 运维
Python装饰器实战场景解析:从原理到应用的10个经典案例
Python装饰器是函数式编程的精华,通过10个实战场景,从日志记录、权限验证到插件系统,全面解析其应用。掌握装饰器,让代码更优雅、灵活,提升开发效率。
130 0

推荐镜像

更多