两个小例子彻底明白python decorator

一:没有什么实际意思,就是单纯的理解decorator。使用装饰器完全可以阻止方法中的代码执行。文章地址https://www.yii666.com/article/758022.html文章来源地址:https://www.yii666.com/article/758022.html

class json_test(object):
def __init__(self, *arg, **args):
self.name = 'default_name'
self.gender = 'default_gender'
self.age =
self.address = None
jt = json_test() class ignore_null_value(object):
def __init__(self, *args, **kwargs):
print('ignore_null_value.init') @staticmethod
def to_json(*arg, **args):
d = {}
for key, value in arg[].__dict__.items():
if value != None:
d.setdefault(key, value)
for key, value in args:
d.setdefault(key, value)
return d class keep_null_value(object):
def __init__(self, *args, **kwargs):
print('keep_null_value.init') @staticmethod
def to_json(o):
return o.__dict__ def deco(c):
def _deco(func):
def __deco(*arg, **args):
print('before')
try:
s = c.to_json(*arg, **args)
return s
finally:
print('after')
return __deco
return _deco class c(object):
@staticmethod
@deco(keep_null_value)
def json_from(self, a):
pass cl = c()
print cl.json_from(jt)

二:输出前后加上log,这个是书中的原例子,哪本书不记得了,不是《python基础教程》就是《python核心编程》文章来源地址https://www.yii666.com/article/758022.html网址:yii666.com<网址:yii666.com

from time import time

def logged(when):
def log(f, *args, **kargs):
print '''Called:
function: %s
args: %r
kargs: %r''' % (f, args, kargs) def pre_logged(f):
def wrapper(*args, **kargs):
log(f, *args, **kargs)
return f(*args, **kargs)
return wrapper def post_logged(f):
def wrapper(*args, **kargs):
now = time()
try:
log(f, *args, **kargs)
return f(*args, **kargs)
finally:
print "time delta: %s" % (time() - now)
return wrapper
try:
return {"pre": pre_logged, "post": post_logged}[when]
except KeyError, e:
raise ValueError(e), 'must be "pre" or "post"' @logged("post")
def hello(name):
print "Hello,", name hello("World!")

版权声明:本文内容来源于网络,版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。文本页已经标记具体来源原文地址,请点击原文查看来源网址,站内文章以及资源内容站长不承诺其正确性,如侵犯了您的权益,请联系站长如有侵权请联系站长,将立刻删除

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信图片_20190322181744_03.jpg

微信扫一扫打赏

请作者喝杯咖啡吧~

支付宝扫一扫领取红包,优惠每天领

二维码1

zhifubaohongbao.png

二维码2

zhifubaohongbao2.png