我正在将一些代码从 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/