python - Python 中函数的条件修饰

标签 python python-3.x python-decorators

出于调试目的,我想编写一个函数来执行此操作:

  1. 如果 debug_mode == 0 不回显任何消息。
  2. 如果 debug_mode == 1 使用 print() 将消息回显到标准输出
  3. 如果 debug_mode == 2 将消息回显到日志文件

我想用函数装饰器(我以前从未使用过)来做到这一点。

实际上,我想替换一些 print(),我在一些点中添加了一些 print() 来向我展示中间值并同时了解函数装饰器。

我不想创建一个类来做到这一点。这是我的方法,但不起作用:

import logging

FORMAT = '%(asctime)s %(levelname)s %(message)s %(funcName)s'
logging.basicConfig(filename='example.log', level=logging.DEBUG, format=FORMAT, datefmt='%m/%d/%Y %I:%M:%S %p')

def debug(func):
    def _debug(deb=0, *args, **kwargs):
        if deb == 1:
            print(msg)
            func(*args, **kwargs)
        if deb == 2:
            logging.debug(msg)
    return _debug

@debug
def echo(msg, deb=0):
    pass

if __name__ == "__main__":
    debug_mode = 1
    echo("This is a debugging message!", debug_mode)

如果我不必传递参数 debug_mode 并且在装饰器函数中我可以直接从 __main__ 使用调试状态,那就更好了。

最佳答案

您的代码的问题在于传递参数的方式。当您执行 echo("This is a debugging message!", debug_mode) 时,您实际上是在调用 def _debug(deb=0, *args, **kwargs) 并且所有参数都困惑了(deb 变成 “这是一条调试消息!” 等)。在 StackOverflow 上有一个惊人的 tutorial关于如何使用装饰器。

我不确定为什么代码中需要 *args, **kwargs 。我个人认为,根据您的具体情况,不需要任何装饰。无论如何,出于教育目的,带有装饰器的工作代码可能看起来像:

import logging

FORMAT = '%(asctime)s %(levelname)s %(message)s %(funcName)s'
logging.basicConfig(filename='example.log', level=logging.DEBUG, format=FORMAT, datefmt='%m/%d/%Y %I:%M:%S %p')

def debug(func):
    def _debug(msg, deb=0):
        if deb == 1:
            func(msg, deb)
        if deb == 2:
            print 'Log: ' + msg + ' Level: ' + str(deb)
            logging.debug(msg)
    return _debug

@debug
def echo(msg, deb):
    print 'Echo: ' + msg + ' Level: ' + str(deb) 

if __name__ == "__main__":
    echo("This is a debugging message!")
    echo("This is a debugging message!", 0)
    echo("This is a debugging message!", 1)
    echo("This is a debugging message!", 2)

输出:

Echo: This is a debugging message! Level: 1
Log: This is a debugging message! Level: 2

关于python - Python 中函数的条件修饰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25640594/

相关文章:

python - xgboost 回归预测相同的值

python - Django/WSGI 应用程序中的持久数据库连接

database - Sentiment140 预处理

python - 出于测试目的访问原始装饰函数

python ( Pandas ): Using decorators using pandas API

Python装饰器添加类级变量

python - PyQt - 使 QAction 可检查,即使它被禁用

python - 无法在Python中将矩阵追加到数组

python - 使用 python 3.6 将多个文件并行加载到内存中的最佳方法是什么?

python-3.x - 在超出范围的索引上打印 “no value”