标签:
def wrap_in_tag_b(fn): # wrap_in_tag_b是真正的装饰器 def wrapped(): return "<b>" + fn() + "</b>" return wrapped def wrap_in_tag_i(fn): def wrapped(): return "<i>" + fn() + "</i>" return wrapped @wrap_in_tag_b @wrap_in_tag_i def hello(): return "hello" print(hello()) # returns "<b><i>hello world</i></b>"
def wrap_in_tag_b(fn): def wrapped(arg): return "<b>" + fn(arg) + "</b>" return wrapped def wrap_in_tag_i(fn): def wrapped(arg): return "<i>" + fn(arg) + "</i>" return wrapped @wrap_in_tag_b @wrap_in_tag_i def hello(name): return "hello {}".formar(name) print(hello(‘Jack‘))
def wrap_in_tag(deco_arg): # 装饰器参数:deco_arg # 可以在任意位置使用 def real_decorator(func): # real_decorator才是即将返回的真正的装饰器 def wrapped() : return "<{0}>{1}</{0}>".format(deco_arg, func()) return wrapped return real_decorator @wrap_in_tag(‘b‘) @wrap_in_tag(‘i‘) def hello(): return "hello" print(hello())
def wrap_in_tag(deco_arg): # 装饰器参数:deco_arg # 可以在任意位置使用 def real_decorator(func): # real_decorator才是即将返回的真正的装饰器 def wrapped(func_arg): # 原函数参数:func_arg # 只可以在此位置使用 return "<{0}>{1}</{0}>".format(deco_arg, func(func_arg)) return wrapped return real_decorator @wrap_in_tag(‘b‘) @wrap_in_tag(‘i‘) def hello(name): return "hello {}".format(name) print(hello(‘Jack‘))
class wrap_in_tag(object): def __init__(self, deco_arg): self.tag = deco_arg def __call__(self, func): def newf(): return "<{0}>{1}</{0}>".format(self.tag, func()) return newf @wrap_in_tag(‘b‘) @wrap_in_tag(‘i‘) def hello(): return ‘hello‘ print(hello())
class wrap_in_tag(object): def __init__(self, deco_arg): self.tag = deco_arg def __call__(self, func): def newf(func_arg): return "<{0}>{1}</{0}>".format(self.tag, func(func_arg)) return newf @wrap_in_tag(‘b‘) @wrap_in_tag(‘i‘) def hello(name): return "hello {}".format(name) print(hello(‘Jack‘))
def wrap_in_tag(deco_arg): # 装饰器参数:deco_arg # 可以在任意位置使用 def real_decorator(func): # real_decorator才是即将返回的真正的装饰器 def wrapped(self, func_arg): # 类方法接收第一个参数都是self,这个必须有,而无论func_arg是否有!!! # 原函数参数:func_arg # 只可以在此位置使用 return "<{0}>{1}</{0}>".format(deco_arg, func(func_arg)) return wrapped return real_decorator class foo(object): @wrap_in_tag(‘b‘) @wrap_in_tag(‘i‘) def hello(self, name): return ‘hello {}".format(name) @wrap_in_tag(‘b‘) @wrap_in_tag(‘i‘) def byebye(self, name): return ‘byebye {}".format(name) f = foo() print(f.hello(‘Jack‘)
class wrap_in_tag(object): def __init__(self, deco_arg): self.tag = deco_arg def __call__(self, func): def newf(slf, func_arg): # slf必须!self被占用了,那就给第一个参数另一个名字slf(随便) return "<{0}>{1}</{0}>".format(self.tag, func(func_arg)) return newf class foo(object): @wrap_in_tag(‘b‘) @wrap_in_tag(‘i‘) def hello(self, name): return ‘hello {}".format(name) @wrap_in_tag(‘b‘) @wrap_in_tag(‘i‘) def byebye(self, name): return ‘byebye {}".format(name)
标签:
原文地址:http://www.cnblogs.com/hhh5460/p/5147103.html