美文网首页工作生活
Python | 装饰器

Python | 装饰器

作者: 简子逍 | 来源:发表于2019-07-02 23:19 被阅读0次

    使用场景

    def decorator(func):
        def wrapper(*args, **kwargs):
            print("start ---")
            func(*args, **kwargs)
            print("--- end")
        return wrapper
    
    def greeting():
        print('Hello')
    
    greeting = decorator(greeting)
    greeting()
    
    # 输出
    start ---
    Hello
    --- end
    

    装饰器 ' @ ' 使用

    def decorator(func):
        def wrapper(*args, **kwargs):
            print("start ---")
            func(*args, **kwargs)
            print("--- end")
        return wrapper
    
    @decorator
    def greeting():
        print('Hello')
    
    greeting()
    
    # 输出
    start ---
    Hello
    --- end
    

    带参数装饰器

    def decorator(user):
        def wrapper1(func):
            def wrapper2(*args, **kwargs):
                print("start ---")
                func(*args, **kwargs)
                print(user)
                print("--- end")
            return wrapper2
        return wrapper1
    
    @decorator(user="Jack")
    def greeting():
        print('Hello')
    
    greeting()
    
    # 输出
    start ---
    Hello
    Jack
    --- end
    

    装饰器类

    class decorator(object):
        def __init__(self, user='Jack'):
            self.user = user
    
        def __call__(self, func):
            def wrapper(*args, **kwargs):
                print("start ---")
                func(*args)
                print(self.user)
                print("--- end")
                return func
            return wrapper
    
    @decorator(user="Jack")
    def greeting():
        print('Hello')
    
    greeting()
    
    # 输出
    start ---
    Hello
    Jack
    --- end
    

    相关文章

      网友评论

        本文标题:Python | 装饰器

        本文链接:https://www.haomeiwen.com/subject/smsxhctx.html