装饰器,闭包。

it2022-05-05  140

闭包

#外部函数outter def outter(): a = 10 # a为inner的外部作用域 #内部函数inner def inner(): print(a) return inner outter()() # 直接调用inner() # 输出为10

如果在内部函数inner中,有对外部作用域的一个引用(a=10),那么内部函数就是一个闭包。在使用时,可以直接调用内部函数,内部函数也照样可以使用外部函数的变量。 作用:保存函数的状态信息,使函数的局部变量信息依然可以保存下来。在爬虫中应用,可闭包将爬取数据保存起来。

装饰器

理解了闭包,就好理解装饰器了。因为装饰器其实是用闭包来实现的。 def handle_exception(fn): def _decorate(): print 'before' fn() print 'after' return _decorate # @为装饰器:其等同于 hello =handle_exception(fn) @handle_exception def hello(): print 'hello' if __name__ == '__main__': print(hello()) 返回结果:test python decorate_sample.py before hello after None

装饰器能大大提高代码的重用性。

原文:https://blog.csdn.net/u012447842/article/details/68556465


最新回复(0)