Python 装饰器、Lambda 与代码性能分析
1. Python 装饰器
在 Python 中,装饰器是一种强大的工具,它允许我们在不修改现有函数代码的情况下,为函数添加额外的功能。装饰器以 @ 符号开头,后面跟着用于“装饰”普通函数的函数名。
以下是一个简单的装饰器示例:
def another_function(func):
"""
A function that accepts another function
"""
def other_func():
val = "The result of %s is %s" % (func(),
eval(func())
)
return val
return other_func
@another_function
def a_function():
"""A pretty useless function"""
return "1+1"
if __name__ == "__main__":
value = a_function()
print(value)
当我们调用 a_function 时,它会被装饰,输出结果为:
The result of 1+1 is 2
超级会员免费看
订阅专栏 解锁全文
1271

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



