代码如下:
# coding=utf-8
from functools import update_wrapper
nums = [1, 2, 3, 4, 5, 6]
def run(num):
"""啦啦,我是run函数"""
num += 1
print num
def test():
"哈哈,我是test函数"
for num in nums:
# func = lambda: run(num)等同于下面的func函数
def func():
"呵呵,我是func函数"
return run(num)
update_wrapper(func, run)
# test.__doc__ = str(num) + 'doc'
# test.__name__ = str(num) + 'name'
# func.description = 'desc'
# print func.description
# func.hehe = 'desc'
# print func.hehe
yield func
if __name__ == "__main__":
for f in test():
f()
print f.__doc__
print f.__name__
# print test.__doc__
# print test.__name__
输出结果:
2
啦啦,我是run函数
run
3
啦啦,我是run函数
run
4
啦啦,我是run函数
run
5
啦啦,我是run函数
run
6
啦啦,我是run函数
run
7
啦啦,我是run函数
run
代码02:
# coding=utf-8
from functools import update_wrapper
nums = [1, 2, 3, 4, 5, 6]
def run(num):
"""啦啦,我是run函数"""
num += 1
print num
def test():
"哈哈,我是test函数"
for num in nums:
def func():
"呵呵,我是func函数"
return run(num)
update_wrapper(func, run)
test.__doc__ = str(num) + 'doc'
test.__name__ = str(num) + 'name'
# func.description = 'desc'
# print func.description
# func.hehe = 'desc'
# print func.hehe
yield func
if __name__ == "__main__":
for f in test():
print '*'*10
f()
# print f.__doc__
# print f.__name__
print test.__doc__
print test.__name__
输出02:
**********
2
1doc
1name
**********
3
2doc
2name
**********
4
3doc
3name
**********
5
4doc
4name
**********
6
5doc
5name
**********
7
6doc
6name
本文通过两个Python代码示例,深入解析了闭包和装饰器的工作原理。首先,展示了如何使用闭包来创建带有状态的匿名函数,并讨论了在函数内部定义函数的场景。其次,介绍了如何利用装饰器更新函数的元数据,如名称和文档字符串,以保持代码的清晰性和可读性。本文适合对Python高级特性感兴趣的开发者。
534

被折叠的 条评论
为什么被折叠?



