Python的装饰器与语法糖

装饰器与语法糖简介

语法糖是一种功能的简化使用,并不改变其功能。对于一个已有函数,如何更新它的功能?Python中使用@作为语法糖,辅助装饰器使用。装饰器函数以函数为参数,内部对原函数进行功能拓展,最后返回一个函数引用。


代码示例

def bar(printA):
    def wrapper(a):
        print("{:*^30}".format('BEGIN'))
        printA(a)
        print("{:*^30}".format('END'))
    return wrapper

@bar
def printA(a):
    print('这是变量{}'.format(a))

printA('python123')

装饰器总结

1、对原函数功能的补充:增加打印等
2、对原函数功能的调整:利用原函数运行结果,再次运算产生新的结果
3、对原函数功能的重写:仅使用原函数名

猜你喜欢

转载自blog.csdn.net/a_13572035650/article/details/128508834