Python中的装饰器是你进入Python大门的一道坎,不管你跨不跨过去它都在那里。
为什么需要装饰器
我们假设你的程序实现了say_hello()和say_goodbye()两个函数。
def say_hello(): print "hello!" def say_goodbye(): print "hello!" # bug here if __name__ == '__main__':
say_hello()
say_goodbye()
但是在实际调用中,我们发现程序出错了,上面的代码打印了两个hello。经过调试你发现是say_goodbye()出错了。老板要求调用每个方法前都要记录进入函数的名称,比如这样:
[DEBUG]: Enter say_hello() Hello!
[DEBUG]: Enter say_goodbye() Goodbye!
好,小A是个毕业生,他是这样实现的。
