首先一个修饰符的实例:
1 #!/usr/bin/env python 2 3 def run(fn): 4 def do_hello(): 5 print "begin..." 6 fn() 7 print "end." 8 return do_hello 9 10 @run 11 def hello(): 12 print "Hello World!" 13 14 if __name__ == '__main__': 15 hello()
修饰符@也可也可以用多個,先加 @run_b 再加@run
@run
@run_b
def hello():
print "hello world!"
上面的例子是在function中使用修饰符,也可以在class中使用修饰符。
1 class entryExit(object): 2 3 def __init__(self, f): 4 self.f = f 5 6 def __call__(self): 7 print "Entering", self.f.__name__ 8 self.f() 9 print "Exited", self.f.__name__ 10 11 @entryExit 12 def func1(): 13 print "inside func1()" 14 15 @entryExit 16 def func2(): 17 print "inside func2()"