python装饰器
python中最不想python风格的就是装饰器了,特别是‘@’很令新来python的人费解,不过装饰器可是很强大的功能。
装饰器语法有两种,类风格和函数风格
类风格例子:
class entryExit(object): def __init__(self, f): self.f = f def __call__(self): print "Entering", self.f.__name__ self.f() print "Exited", self.f.__name__@entryExitdef func1(): print "inside func1()"@entryExitdef func2(): print "inside func2()"func1()func2()
Entering func1inside func1()Exited func1Entering func2inside func2()Exited func2
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()print func1.__name__
def entryExit(f): def new_f(): print "Entering", f.__name__ f() print "Exited", f.__name__ new_f.__name__ = f.__name__ return new_f