装饰器

装饰器:又叫包装函数

作用: 1. 添加说明,提醒等. 2. 添加登,验证陆装饰器

原理是在执行student时会把student作为deco的参数传到deco中执行,student函数在deco的子函数wrapper中做为参数被执行.(即在装饰器的装饰下执行函数)

def deco(func):

    def wrapper():

        print("======start====")

        func()

        print("======end====")

    return wrapper

@deco

def student():

    print ("student")

student()

 

#加了装饰器,函数就作为装饰器的参数被执行,通过wrapper返回结果

 

注意:解决形参问题,在装饰器中用可变参数

def deco(func):

    def wrapper(*args):

        print("======start====")

        func(*args)

        print("======end====")

    return wrapper

 

@deco

def student(name, age):

    print("student info name is {} age {}".format(name, age))

 

student("guohongze", 35)

 

完整装饰器:

def logging(level):

    def wrapper(func):

        def inner_wrapper(*args, **kwargs):

            print("[{level}]: enter function {func}()".format(

                level=level,

                func=func.__name__))

            return func(*args, **kwargs)

        return inner_wrapper

    return wrapper

 

@logging(level='INFO')

def say(something):

    print("say {}!".format(something))

 

 

@logging(level='INFO')

def hello(name, age, sex):

    print("hello student")

    print("your name is {}".format(name))

    print("your age is {}".format(age))

    print("your sex is {}".format(sex))

 

say("hello world!")

hello("hf", 35, "male")

posted on 2019-11-13 15:56  锋锋2019  阅读(78)  评论(0编辑  收藏  举报

导航