本文共 3385 字,大约阅读时间需要 11 分钟。
def wrap_in_tag_b(fn): # wrap_in_tag_b 是真正的装饰器 def wrapped(): return "" + fn() + "" return wrappeddef wrap_in_tag_i(fn): def wrapped(): return "" + fn() + "" return wrapped@wrap_in_tag_b@wrap_in_tag_idef hello(): return "hello"print(hello()) # returns "hello world"
def wrap_in_tag_b(fn): def wrapped(arg): # arg 是原函数参数 return "" + fn(arg) + "" return wrappeddef wrap_in_tag_i(fn): def wrapped(arg): # arg 是原函数参数 return "" + fn(arg) + "" return wrapped@wrap_in_tag_b@wrap_in_tag_idef hello(name): return "hello {}".formar(name)print(hello('Jack'))
def wrap_in_tag(deco_arg): # 装饰器参数:deco_arg # 可以在任意位置使用 def real_decorator(func): # real_decorator才是即将返回的真正的装饰器 # 原函数参数:func_arg # 只可以在此位置使用 def wrapped() : return "<{0}>{1} ".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} ".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 # 装饰器参数:deco_arg def __call__(self, func): def newf(): # 原函数无参数 return "<{0}>{1} ".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 # 装饰器参数:deco_arg def __call__(self, func): def newf(func_arg): # 原函数参数: func_arg return "<{0}>{1} ".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): def real_decorator(func): def wrapped(self, func_arg): # 类方法接收第一个参数都是self,这个必须有,而无论func_arg是否有!!! return "<{0}>{1} ".format(deco_arg, func(func_arg)) return wrapped return real_decoratorclass 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} ".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)
f = foo()print(f.hello('Jack'))
本文转自罗兵博客园博客,原文链接:http://www.cnblogs.com/hhh5460/p/5147103.html,如需转载请自行联系原作者