一:没有什么实际意思,就是单纯的理解decorator。使用装饰器完全可以阻止方法中的代码执行。
class json_test(object): def __init__(self, *arg, **args): self.name = 'default_name' self.gender = 'default_gender' self.age = 0 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[0].__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核心编程》
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!")