Python 函数装饰器

1、python中可以将一个函数赋值给一个变量

def hi(name='yasoob'):
    return "hi"+name
print(hi())   #hi  yasoob

greet=hi  #注意这里hi后面没有小括号
print(greet())   #hi  yasoob

del hi    #如果我们删掉旧的hi函数,看看会发生什么!
print(greet())    ##hi  yasoob
print(hi())    #报错:NameError: name 'hi' is not defined

2、在函数中定义函数:在 Python 中我们可以在一个函数中定义另一个函数:

def hi(name='yasoob'):
    print("now you are inside the hi() function")
    
    def greet():
        return "now you are in the greet() function"
    
    def welcome():
        return "now you are in the welcome() function"
    
    print(greet())
    print(welcome())
    print("now you are back in the hi() function")

#上面展示了无论何时你调用hi(), greet()和welcome()将会同时被调用
hi()    
#now you are inside the hi() function
#now you are in the greet() function
#now you are in the welcome() function
#now you are back in the hi() function

#然后greet()和welcome()函数在hi()函数之外是不能访问的
greet()    #报错:NameError: name 'greet' is not defined

1)上面展示了无论何时你调用hi(), greet()和welcome()将会同时被调用。

2)然后greet()和welcome()函数在hi()函数之外是不能访问的

3、从函数中返回函数:

def hi1(name='yasoob'):
    def greet():
        return "now you are in the greet() function"

    def welcome():
        return "now you are in the welcome() function"

    if name=='yasoob':
        return greet     #注意这里没有小括号
    else:
        return welcome    #注意这里没有小括号

a=hi1()
print(a)    #<function hi1.<locals>.greet at 0x000001D0654520D8>    这里清晰地展示了`a`现在指向到hi()函数中的greet()函数
print(a())   #now you are in the greet() function   #相当于print(greet())
print(hi1('navy')())   #now you are in the welcome() function    #相当于print(welcome())

再次看看这个代码。在 if/else 语句中我们返回 greet 和 welcome,而不是 greet() 和 welcome()。为什么那样?这是因为当你把一对小括号放在后面,这个函数就会执行;然而如果你不放括号在它后面,那它可以被到处传递,并且可以赋值给别的变量而不去执行它。 你明白了吗?让我再稍微多解释点细节。

当我们写下 a = hi(),hi() 会被执行,而由于 name 参数默认是 yasoob,所以函数 greet 被返回了。如果我们把语句改为 a = hi(name = "navy"),那么 welcome 函数将被返回。我们还可以打印出 hi()(),这会输出 now you are in the greet() function

4、将函数作为参数传给另一个函数

def hi():
    return "hi yasoob!"

def dosomthingBeforeHi(func):
    print("I am doing some boring work before executing hi()")
    print(func())

dosomthingBeforeHi(hi)   
#I am doing some boring work before executing hi()
#hi yasoob!

5、第一个装饰器:装饰器让你在一个函数的前后去执行代码

def a_new_decorator(a_func):

    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")

        a_func()

        print("I am doing some boring work after executing a_func()")

    return wrapTheFunction

def a_function_requiring_decoration():
    print("I am the function which needs some decoration to remove my foul smell")


a_function_requiring_decoration()  #I am the function which needs some decoration to remove my foul smell

a_function_requiring_decoration=a_new_decorator(a_function_requiring_decoration)

a_function_requiring_decoration()   
#I am doing some boring work before executing a_func()
#I am the function which needs some decoration to remove my foul smell
#I am doing some boring work after executing a_func()

我们刚刚应用了之前学习到的原理。这正是 python 中装饰器做的事情!它们封装一个函数,并且用这样或者那样的方式来修改它的行为

6、运用@符号:

def a_new_decorator(a_func):

    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")

        a_func()

        print("I am doing some boring work after executing a_func()")

    return wrapTheFunction

@a_new_decorator
def a_function_requiring_decoration():
    print("I am the function which needs some decoration to remove my foul smell")


a_function_requiring_decoration()
#I am doing some boring work before executing a_func()
#I am the function which needs some decoration to remove my foul smell
#I am doing some boring work after executing a_func()


print(a_function_requiring_decoration.__name__)   #wrapTheFunction

这并不是我们想要的!Ouput输出应该是"a_function_requiring_decoration"。这里的函数被warpTheFunction替代了。它重写了我们函数的名字和注释文档(docstring)。幸运的是Python提供给我们一个简单的函数来解决这个问题,那就是functools.wraps。我们修改上一个例子来使用functools.wraps:

from functools import wraps
def a_new_decorator(a_func):
    @wraps(a_func)
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
        a_func()
        print("I am doing some boring work after executing a_func()")
    return wrapTheFunction

@a_new_decorator
def a_function_requiring_decoration():
    "hey you!Decorate me!"
    print("I am the function which needs some decoration to remove my foul smell")

print(a_function_requiring_decoration.__name__)   # a_function_requiring_decoration

 蓝本规范:

from functools import wraps
def decorator_name(f):
    @wraps(f)
    def decorated(*args,**kwargs):
        if not can_run:
            return "Function will not run"
        return f(*args,**kwargs)
    return decorated

@decorator_name
def func():
    return("Function is running")

can_run=True
print(func())   #Function is running

can_run=False
print(func())   #Function will not run

注意:@wraps接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等等的功能。这可以让我们在装饰器里面访问在装饰之前的函数的属性。

*args和*kwargs是python中经常使用的函数参数,代表着函数的参数数目是可变的。 

def fun(*args,**kwargs):
    print("args= ",args)
    print("kwargs= ",kwargs)

fun(1,2,3,4)  
#args=  (1, 2, 3, 4)
#kwargs=  {}

fun(a=1,b=2,c=3,d=4)
#args=  ()
#kwargs=  {'a': 1, 'b': 2, 'c': 3, 'd': 4}

fun(1,2,3,4,a=1,b=2,c=3,d=4)

#args=  (1, 2, 3, 4)
#kwargs=  {'a': 1, 'b': 2, 'c': 3, 'd': 4}

fun(4,5,6,'hello',a='qwe',b='asd',c='zxc')
#args=  (4, 5, 6, 'hello')
#kwargs=  {'a': 'qwe', 'b': 'asd', 'c': 'zxc'}

#在函数的参数同时有*args和**kwargs时,args的使用必须要在kwargs的前面

日志运用到装饰器上:

def logit(func):
    @wraps(func)
    def with_logging(*args,**kwargs):
        print(func.__name__+"was called")
        return func(*args,**kwargs)
    return with_logging

@logit
def addition_func(x):
    return x+x

result=addition_func(4)  #addition_funcwas called

带参数的装饰器,

在函数中嵌入装饰器

我们回到日志的例子,并创建一个包裹函数,能让我们指定一个用于输出的日志文件。

from functools import wraps

def logit(logfile='out.log'):
    def logging_decorator(func):
        @wraps(func)
        def wrapped_function(*args,**kwargs):
            log_string=func.__name__+"was called"
            print(log_string)
            with open(logfile,'a') as opened_file:
                opened_file.write(log_string+'\n')
            return func(*args,**kwargs)
        return wrapped_function
    return logging_decorator
@logit()
def myfunc1():
    pass

myfunc1()  #myfunc1was called

@logit(logfile='func2.log')
def myfunc2():
    pass

myfunc2()   #myfunc2was called

生成了两个文件:out.log和func2.log

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值