python class decorator with parameters

Excerpt: https: //www.cnblogs.com/zhzhang/p/11375774.html

 

# -*- coding: utf-8 -*-
# Author: baoshan
# Decorator with parameters class (class decorators and no parameters are very different)
# Class decorators to achieve, and must implement __call__ __init__ two built-in functions.
# __Init__: no longer receive decorative function, but receives incoming parameters;
# __Call__: receiving decorative function, the logic implemented decorative


class logger(object):
    def __init__(self, level='INFO'):
        self.level = level

    def __call__(self, func):
        def wrapper(*args, **kwargs):
            print("[{level}]: the function {func}() is running...".format(level=self.level, func=func.__name__))
            func(*args, **kwargs)
        return wrapper


@logger(level="WARNING")
def say(something):
    print("say {}!".format(something))


say("hello")

  

 

Guess you like

Origin www.cnblogs.com/LiuYanYGZ/p/12169356.html