Last active
August 29, 2015 14:23
-
-
Save tawateer/8fa7afbe36e8e736c7a5 to your computer and use it in GitHub Desktop.
decorator 例子
This file contains hidden or 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
#!/usr/bin/python | |
#-*- coding: utf-8 -*- | |
""" | |
output: | |
execute now1(): | |
2013-12-25 | |
call now2(): | |
2013-12-25 | |
""" | |
import functools | |
def log(arg): | |
if callable(arg): | |
# @log 模式 | |
func = arg | |
@functools.wraps(func) | |
def wrapper(*args, **kw): | |
print 'call %s():' % func.__name__ | |
return func(*args, **kw) | |
return wrapper | |
else: | |
# @log('arg') 模式 | |
def decorator(func): | |
@functools.wraps(func) | |
def wrapper(*args, **kw): | |
print '%s %s():' % (arg, func.__name__) | |
return func(*args, **kw) | |
return wrapper | |
return decorator | |
@log('execute') | |
def now1(): | |
print '2013-12-25' | |
@log | |
def now2(): | |
print '2013-12-25' | |
if __name__ == "__main__": | |
now1() | |
now2() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment