def decorator(fun):
def call(*args, **kwargs):
print "do something before fun!"
if len(args) < 1:
print "args is less"
else:
fun(args[0])
print "do something after fun!"
return call
@decorator
def hello(a):
print "hello"
# hello(*args, **kwargs)
# is equivalent to
# decorator(hello)(*args, **kwargs)
# see the example for more detail
print "hello() is called:"
hello()
print "-----------------------------"
print "hello(1) is called:"
hello(1)
def chain1(fun):
def call(*args1, **kwargs1):
print "chain1"
fun(*args1, **kwargs1)
return call
@chain0
@chain1
def chain2(*args2, **kwargs2):
print "chain2"
# attention!!
# chain2(*args0, **kwargs0)
# is equivalent to chain0(chain1(chain2))(*args0, **kwargs0)
# it is not chain2(*args2, **kwargs2)
# it is not chain0(chain1(chain2(*args0, **kwargs0)))
# it is not chain0(chain1(chain2(*args2, **kwargs2)))
chain2()
运行结果:
hello() is called:
do something before fun!
args is less
do something after fun!
-----------------------------
hello(1) is called:
do something before fun!
hello
do something after fun!
chain0
chain1
chain2
具体原因看注释就明白了。 decorator是类时,