简体   繁体   中英

Why does the python decorator function nest a function?

def log(func):
     def wrapper(*args, **kw):
         print('call %s():' % func.__name__) 
         return func(*args, **kw)
     return wrapper
@log
def now():
     print('2017-5')

Why in the middle to nest wrapper function, why not?It's my first questions in stackoverflow and I'm not good at English .so my description hava any problem ,please forgive me .Thanks!!!

def log(func):
    print('call %s():' % func.__name__)
    return func(*args, **kw)
@log
def now():
    print('2017-5')

A bit about decorators:

@decorator
def func():
    ...

exactly equals to:

func = decorator(func)

As you can notice, in the first option print('call %s():' % func.__name__) will be called any time when your function now is called in your program. In the second option, this print will be called when decorator applies only without calling now .

Nested function is used because decorator replaces the original function with the modified one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM