[python]装饰器的使用

1、前言

使用装饰器将函数作为参数,最后再返回一个参数,简单来说就是在不修改原函数的代码上对原函数添加新的功能。

2、实测用例

(1)在原函数中添加一个装饰器

原函数:

def SayHello():
    print("Hello,World")

SayHello()

添加装饰器后:

import functools

def decorator(fun):                      #fun为调用的函数
    @functools.wraps(fun)
    def wrapper(*args,**kwargs):
        print("Hello,Python")            #添加的功能
        fun(*args,**kwargs)
    return wrapper                       #调用添加功能的函数

@decorator
def SayHello():
    print("Hello,World")

SayHello()

1、@decorator相当于SayHello = decorator(SayHello)

2、*args,**kwargs   表示可以接受任意的参数

3、@functools.wraps(fun) 保存原函数的属性,如name,model等

(2)在原函数中添加多个装饰器

import functools

def decorator(fun):                                #fun为调用的函数
    @functools.wraps(fun)
    def wrapper(*args,**kwargs):
        print("Hello,Python")                     #添加的功能
        fun(*args,**kwargs)
    return wrapper                                #调用添加功能的函数

def decorator1(fun):
    @functools.wraps(fun)
    def wrapper(*args,**kwargs):
        print("I Lov Study")
        fun(*args,**kwargs)
    return wrapper


@decorator1
@decorator
def SayHello():
    print("Hello,World")

SayHello()

调用方式:

SayHello = decorator1(SayHello)

SayHello = decorator(SayHello)

(3)装饰器传入参数

import functools

def GetNum(num):
    def decorator(fun):                           #fun为调用的函数
        @functools.wraps(fun)
        def wrapper(*args,**kwargs):
            print("Hello,Python")                 #添加的功能
            print("Getnum %d"%(int(num)))
            fun(*args,**kwargs)
        return wrapper                           #调用添加功能的函数
    return decorator



@GetNum('10')                                    #传入参数
def SayHello():
    print("Hello,World")

SayHello()

注:只需再填写一个高阶函数返回decorator即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值