本文共 2543 字,大约阅读时间需要 8 分钟。
按别人的教程弄的。
要清楚基于类和基于函数的实现的不同之处。
#!/usr/bin/env python# -*- coding: utf-8 -*-'''class entryExit(object): def __init__(self, f): self.f = f def __call__(self): print "Enering", self.f.__name__ self.f() print "Exited", self.f.__name__def entryExit(f): def new_f(): print "Entering", f.__name__ f() print "Exited", f.__name__ return new_f@entryExitdef func1(): print "inside func1()"@entryExitdef func2(): print "inside func2()"func1()func2()class decoratorWithoutArguments(object): def __init__(self, f): print "Inside __init__()" self.f = f def __call__(self, *args): print "Inside __call__()" self.f(*args) print "After self.f(*args)"@decoratorWithoutArgumentsdef sayHello(a1, a2, a3, a4): print 'sayHello arguments:', a1, a2, a3, a4print "After decoration"print "Preparing to call sayHello()"sayHello("say", "hello", "argument", "list")print "After first sayHello() call"sayHello("a", "different", "set of", "arguments")print "After second sayHello() call"class decoratorWithArguments(object): def __init__(self, arg1, arg2, arg3): print "Inside __init__()" self.arg1 = arg1 self.arg2 = arg2 self.arg3 = arg3 def __call__(self, f): print "Inside __call__()" def wrapped_f(*args): print "Inside wrapped_f()" print "Decorator arguments:", self.arg1, self.arg2, self.arg3 f(*args) print "After f(*args)" return wrapped_f@decoratorWithArguments("hello", "world", 42)def sayHello(a1, a2, a3, a4): print 'sayHello arguments:', a1, a2, a3, a4print "After decoration"print "Preparing to call sayHello()"sayHello("say", "hello", "argument", "list")print "After first sayHello() call"sayHello("a", "different", "set of", "arguments")print "After second sayHello() call"'''def decoratorFunctionWithArguments(arg1, arg2, arg3): def wrap(f): print "Inside wrap()" def wrapped_f(*args): print "Inside wrapped_f()" print "Decorator arguments:", arg1, arg2, arg3 f(*args) print "After f(*args)" return wrapped_f return wrap@decoratorFunctionWithArguments("Hello", "world", 42)def sayHello(a1, a2, a3, a4): print 'sayHello arguments:', a1, a2, a3, a4print "After decoration"print "Preparing to call sayHello()"sayHello("say", "hello", "argument", "list")print "After first sayHello() call"sayHello("a", "different", "set of", "arguments")print "After second sayHello() call"
转载地址:http://bgjmo.baihongyu.com/