装饰器的高级用法?

首先, 定义了一个装饰器:

def db_wrap(method):
    @functools.wraps(method)
    def _wrapper(*args, **kwargs):
        # 数据库的连接
        conn = Mysql().connection
        cursor = conn.cursor()
        try:
            cursor.execute("BEGIN")
            retval = method(cursor, *args, **kwargs)
            cursor.execute("COMMIT")
        except:
            cursor.execute("ROLLBACK")
            raise
        finally:
            cursor.close()
            conn.close()
        return retval
    return _wrapper 

  

  

然后去装饰了一个函数,函数是通过sql语句查某张表的数据,函数是这样的

@db_wrap
def get_data_by_index(cursor, exec_sql):
    cursor.execute(exec_sql)
    res = cursor.fetchall()
    res = list(res) if res else []
    return res

  

最后调用的时候,是这样的

sql = '''SELECT * FROM WFXX WHERE CLXXBH > %d AND CLXXBH <= %d  ORDER BY CLXXBH'''
get_data_by_index(sql)

我调用的时候只传了一个参数,但原函数是要接收两个参数的

函数体中的确有 cursor 和 exec_sql 两个参数,得到的结果也是正确的

问题如下:

1.装饰器改变了函数的传参,原本要传两个参数的,现在只需传一个了,装饰器赠送了  cursor 参数

2.装饰器的原理不是说在不影响原函数的情况下,增加额外逻辑,显然这个装饰器违反了规则

猜你喜欢

转载自www.cnblogs.com/kaichenkai/p/10525737.html