python中的Decorator的使用
无参数Decorator类
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)"
@decoratorWithoutArguments
def sayHello(a1, a2, a3, a4):
print 'sayHello arguments:', a1, a2, a3, a4
print "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"
无参数 Decorator函数
def entryExit(f):
def new_f():
print "Entering", f.__name__
f()
print "Exited", f.__name__
return new_f
@entryExit
def func1():
print "inside func1()"
带参数Decorator类
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, a4
print "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"
带参数 Decorator函数
def dec(word):
def wrap(app):
def wrap_f(*arg):
app(word + arg[0])
return wrap_f
return wrap
@dec('hello')
def pword(w):
print w
pword('xixi')
def dec2(app):
def wrap_f(*arg):
app(word + arg[0])
return wrap_f
@dec2
def pword2(w):
print w
pword('xixi2')