Python函数修饰符@的详细教程

Python函数修饰符@的作用是为现有的函数增加额外的功能;其作用非常强大,今天我们就来谈谈它是如何在日志记录中起到很好的作用的。

先看一个例子:

import datetime

__DEBUG__ = True

def log(func):
    if __DEBUG__:
        print('函数开始于',datetime.datetime.now())
        
    func()
    
    if __DEBUG__:
        print('函数结束于',datetime.datetime.now())

def test():
    
    print('test')
    test_lst = []
    for i in range(100):
        test_lst.append(i)

log(test)

log() 是一个日志函数,用于记录函数运行的开始时间,和结束时间。

可是这段代码有个弊端,在测试某个函数时,我们需要添加类似于log(test)这样的代码,不需要后把它删除;这样做很麻烦。

还好我们有@函数装饰符。修改前文中的代码,移除 log(text).

在test函数的上方加入@log装饰器。

@log
def test():
    pass

这段代码和前文中的代码功能是一样的。

可是问题又来了;运行上述代码,发现我们没有调用test函数,test就已经被执行了,因为@log等于log(test),有什么方法让它只有在我们调用的时候运行呢?修改代码:

import datetime

__DEBUG__ = True

def log(func):
    def wrapper():
        if __DEBUG__:
            print('函数开始于',datetime.datetime.now())
        
        func()
    
        if __DEBUG__:
            print('函数结束于',datetime.datetime.now())
    return wrapper

@log
def test():
    
    print('test')
    test_lst = []
    for i in range(100):
        test_lst.append(i)

我在log函数中定义了一个wrapper函数对原功能进行包装,并将这个函数返回。

在不使用装饰器的情况下,你需要这样才能让函数运行:

log(test)()

在使用@log装饰器后,直接调用test()即可获取函数运行日志,我们可以为很多需要测试的函数添加@log装饰器,不需要用这个功能直接将__DEBUG__设置成False。

它的执行顺序是这样的:在为函数添加了@log装饰器后,log函数就被执行,而使用了@log装饰器的 test 函数被作为log函数的传入值使用,在log函数中,对test函数进行了一个简单的包装,并将包装好的函数返回,也就是log函数中的wrapper函数;此时test函数实际变成了wrapper函数。

如何给函数添加参数

前文中的test 函数是没有使用参数的,如果你要定义和使用参数,应该这样修改:

def test(a,b):
    
    print('test')
    test_lst = []
    for i in range(a):
        test_lst.append(i*b)
test(1,2)

包装函数:

    def wrapper(*args,**kwargs):
        if __DEBUG__:
            print('函数开始于',datetime.datetime.now())
        
        func(*args,**kwargs)
    
        if __DEBUG__:
            print('函数结束于',datetime.datetime.now())

*args是将参数以元组的形式打包成tuple给函数体调用;

**kwargs是将关键字参数打包成dict给函数体调用;

为@log装饰器添加参数

有这样一种场景:

fp = open('out.log','a')

@log(level=1,file=fp)
@log(1,fp)

怎么能让装饰器拥有参数呢?

import sys

fp = open('out.log','a')

def log(level=1,file=sys.stdout):
    def _log(func):
        def wrapper(*args,**kwargs):
            if __DEBUG__:
                print('函数开始于',datetime.datetime.now(),file=file,flush=True)
        
            func(*args,**kwargs)
    
            if __DEBUG__:
                print('函数结束于',datetime.datetime.now(),file=file,flush=True)
        return wrapper
    return _log
@log(file=fp)

现在你可以指定日志的输出文件了。

为@log装饰器添加方法

又有这样的场景:

@log.sendto('127.0.0.1:9009'.timeout=30)

你可以将.sendto方法理解为将日志发送到指定服务器;

那么log函数就开始有点虚脱了,虽然有方法在log函数中实现这一目的,但是比较复杂,有一种更简单的方法,就是将log函数转换成类:

class _log:
    def __call__(self,level=1,file=sys.stdout):
        def _log_wrapper(func):
            def wrapper(*args,**kwargs):
                if __DEBUG__:
                    print('函数开始于',datetime.datetime.now(),file=file,flush=True)
        
                func(*args,**kwargs)
    
                if __DEBUG__:
                    print('函数结束于',datetime.datetime.now(),file=file,flush=True)
            return wrapper
        return _log_wrapper

使用前别忘记实例化,log=_log()

现在只需要在_log类中定义方法,即可向@log装饰器添加方法:

    def sendto(self,addr,timeout=20):
        
        pass

完整源码:

import datetime
import sys
__DEBUG__ = True

class _log:
    def __call__(self,level=1,file=sys.stdout):
        def _log_wrapper(func):
            def wrapper(*args,**kwargs):
                if __DEBUG__:
                    print('函数开始于',datetime.datetime.now(),file=file,flush=True)
        
                func(*args,**kwargs)
    
                if __DEBUG__:
                    print('函数结束于',datetime.datetime.now(),file=file,flush=True)
            return wrapper
        return _log_wrapper
    
    def sendto(self,addr,timeout=20):
        pass
    
log=_log()


fp = open('out.log','a')

@log(file=fp)
def test(a,b):
    
    print('test')
    test_lst = []
    for i in range(a):
        test_lst.append(i*b)

test(1,2)

原创内容,如需转载,请注明出处;

本文地址: https://www.perfcode.com/p/956.html

分类: 计算机技术
推荐阅读:
Microsoft Office 禁用自动更新方法 近日,作者发现 Microsoft Office会偷偷摸摸的自动安装更新,这点是我无法忍受的,因为像这样的大型软件,随随便便更新以下就是几百兆的更新包,不仅占用网络资源,而且对我心爱的固态硬盘极为不利,而且这些软件更新推送很频繁;
ValueError: complex() arg is a malformed string解决办法 在Python使用complex()函数对字符串进行转换时,字符串在+或-的周围必须不能有空格。例如complex('1+2j')是合法的,但complex('1 + 2j')会触发ValueError异常。
MySQL ERROR 1062错误出现原因及解决方法 当一个字段被设置成了主键(Primary Key)或唯一索引(Unique Index)时,那么该字段的数据不能重复;如果尝试插入已有数据,将产生1062错误;
Python breakpoint()函数详细教程 brekpoint()函数是python3.7版本新增的一个内置函数;该函数会在调用时使程序进入调试器中;
Linux终端如何输入复杂的命令 在Linux下,当你要输入的命令过于复杂,比如有许多参数,你可以先按 ctrl + x ,再按 ctrl + e 快速打开一个编辑器编辑命令。
使用pyi-bindepend工具查看EXE文件的依赖库 pyi-bindepend.exe工具是PyInstaller的一个附属工具,其功能是获得EXE文件运行时需要的依赖文件,当丢失这些文件时,程序无法运行。