Created
February 18, 2016 09:57
-
-
Save ferstar/9fc4d714f9739509f155 to your computer and use it in GitHub Desktop.
廖雪峰博客 Python3 教程练习
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'''装饰器 | |
在函数调用的前后打印出'begin call'和'end call'的日志; | |
即支持@log又支持@log('xxx')的调用 | |
''' | |
import functools | |
def log(arg): | |
def decorator(func=arg): | |
text = 'call' if func == arg else arg | |
@functools.wraps(func) | |
def wrapper(*args, **kw): | |
print('%s begin call %s()' % (text,func.__name__)) | |
temp = func(*args, **kw) | |
print('end call %s()' % func.__name__) | |
return temp | |
return wrapper | |
return decorator() if callable(arg) else decorator | |
@log('hello') | |
def now(): | |
pass | |
now() | |
@log | |
def hello(): | |
print('hello world!') | |
hello() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment