python装饰器

本文深入讲解了Python中装饰器的概念及应用。通过多个实例演示如何使用装饰器在不修改原始函数的基础上添加新功能,包括基本装饰器的使用、带参数的装饰器函数等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 函数装饰器定义

python装饰器本质上就是一个函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外的功能;

装饰器的返回值也是一个函数对象(函数的指针)

  • 例子:
def startEnd(fun):     #函数命名的规则,驼峰
    def wraper():
        print("!!!!!!!start!!!!!!!!!")
        fun()
        print("!!!!!!!end!!!!!!!!!")
    return wraper

@startEnd
def hello():
    print("hello world")

hello()

脚步输出:

  • 装饰器的作用
1. 在不改变源代码的情况下,给现有的函数增加新的功能
2. 装饰器通过@(符号)进行使用 ,相当于把hello() 函数作为参数,传给startEnd()
3. @startEnd  相当于    hello = startEnd(hello)

4. 当你调用hello()的时候,是不是就相当于调用了startEnd(hello())()

  • 装饰器的属性特点

实质: 是一个函数
参数:是你要装饰的函数名(并非函数调用)
返回:是装饰完的函数名(也非函数调用)
作用:为已经存在的对象添加额外的功能
特点:不需要对对象做任何的代码上的变动

  • 装饰器的写法

例子1:

def hello():
    print("!!!!!!!!!start!!!!!!!!")
    print("hello world")
    print("!!!!!!!!end!!!!!!!!!")

a = hello()   #hello函数把返回值 赋予 a
print("#####################")
b = hello    #b是一个函数, b()相当于hello()
print("@@@@@@@@@@")
b()

输出结果:

例2:

def startEnd(fun):
    def aa(name):
        print("*********start*******")
        fun(name)
        print("*********end*******")
    return aa
# 返回值 aa函数
# hello()  相当于执行 hello()

@startEnd
#装饰器
def hello(name):
    print("hello {0}".format(name))

hello("hewj")
结果输出:

理解思路
 1. aa = startEnd(hello)
 2. hello = aa

 3. 调用hello()

例3:带参数的装饰器函数

def startEnd(author):
    def a(fun):
        def b(name):
            print("This author is {0}".format(author))
            print("*************start**********")
            fun(name)
            print("**************end***********")
        return b
    return a
@startEnd("hewj")
def hello(name):
    print("hello {0}".format(name))
输出:

     




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值