python - 在 python 中包装一个函数,提供一个额外的 bool 值

标签 python wrapper

我正在将一些代码从 Perl 移植到 Python,我正在移动的函数之一执行以下操作:

sub _Run($verbose, $cmd, $other_stuff...)
{
  ...
}

sub Run
{
  _Run(1, @_);
}

sub RunSilent
{
  _Run(0, @_);
}

所以要用Python来做,我天真地以为我可以做到以下几点:

def _Run(verbose, cmd, other_stuff...)
  ...

def Run(*args)
  return _Run(True, args);

def RunSilent
  return _Run(False, args);

但这不起作用,因为 args 是作为数组/元组传递的。为了让它工作,我做了以下事情:

def _Run(verbose, cmd, other_stuff...)
  ...

def Run(*args)
  return _Run(True, ','.join(args));

def RunSilent
  return _Run(False, ','.join(args));

但这看起来有点丑陋。有没有更好的办法?

最佳答案

* 可用于 passing (positional) arguments也是。

def Run(*args):
  return _Run(True, *args)

请注意,只有这样,您才能调用带有关键字参数的函数。为了支持它们,还需要包含 **:

def Run(*args, **kwargs):
  return _Run(True, *args, **kwargs)

实际上你可以将函数声明为

def run(cmd, other_stuff, silent=False):
   ...

那么它可以被称为

run("foo", etc)               # Run
run("foo", etc, silent=True)  # RunSilent

关于python - 在 python 中包装一个函数,提供一个额外的 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3602938/

相关文章:

Python pandas 汇总表图

python - 无法制作指定大小的列表列表

c# - .Net 的 Windows API 包装器?

c# - 在 Python 中为 C# 库创建包装器

java - 将 Streams 与原始数据类型和相应的包装器一起使用

python - 错误 : double-linked list on Raspberry PI3

python - metpy.units 函数有问题吗?

Python:计算pi时为 "long int too large to convert to float"

java - 我如何在类上应用 JNI 而不是将随机函数组合在一起?

Java "double cannot be dereferenced"错误 - 在 double 据类型上调用方法