python - 如何像 JavaScript 一样在 Python 中包装函数?

标签 python python-3.x

我想创建一个执行打印的新函数,前提是Debug=True。这就是我在 JavaScript 中的做法:

function log(...args) {
    if (debug) console.log.apply(null,args)
}

 function log() {
        if (debug) console.log.apply(null,arguments)
    }

如何在 Python 中做类似的事情?

问题:如何传递我在 Python 中获得的所有参数?

最佳答案

您可以使用可变参数和可变关键字参数:

# assuming debug is a global variable initialized as either True or False
def log(*args, **kwargs):
    if debug:
        print(*args, **kwargs)

关于python - 如何像 JavaScript 一样在 Python 中包装函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52695394/

相关文章:

python-3.x - 当我想要出现索引时如何使用 numpy.hist

python - 将键值对添加到嵌套字典

python - Python错误处理重试代码

python - 使用 Python 在嵌套字典中查找键

python - 使用字典理解和 eval() 创建字典给我 NameError

python - 如何在 MySQL Workbench for Mac (Big Sur) 中添加系统路径路径

python - 选择 numpy 数组,使最后一个元素为 1

python - 如何让Python自动允许端口通过Windows防火墙

"print()"内的 Python 整数乘法

python - 为什么我得到 "dlib isn' t going to use CUDA"when I compile dlib python interface