Python 列表为 *args?
我有两个 Python 函数,它们在函数定义中都采用变量参数。举一个简单的例子:
def func1(*args):
for arg in args:
print arg
def func2(*args):
return [2 * arg for arg in args]
我想组合它们 - 就像 func1(func2(3, 4, 5))
一样 - 但我不想要 args
在 func1
中为 ([6, 7, 8],)
,我希望它为 (6, 7, 8)
,就好像它被称为 func1(6, 7, 8)
而不是 func1([6, 7, 8])
一样。
通常,我只使用 func1(*func2(3, 4, 5))
或让 func1
检查是否 args[0]
是一个清单。不幸的是,我无法在这个特定实例中使用第一个解决方案,并且应用第二个解决方案需要在许多地方进行这样的检查(有很多函数充当 func1
的角色)。
有人知道如何做到这一点吗?我想可以进行某种内省,但我可能是错的。
I have two Python functions, both of which take variable arguments in their function definitions. To give a simple example:
def func1(*args):
for arg in args:
print arg
def func2(*args):
return [2 * arg for arg in args]
I'd like to compose them -- as in func1(func2(3, 4, 5))
-- but I don't want args
in func1
to be ([6, 7, 8],)
, I want it to be (6, 7, 8)
, as if it was called as func1(6, 7, 8)
rather than func1([6, 7, 8])
.
Normally, I would just use func1(*func2(3, 4, 5))
or have func1
check to see if args[0]
was a list. Unfortunately, I can't use the first solution in this particular instance and to apply the second would require doing such a check in many places (there are a lot of functions in the role of func1
).
Does anybody have an idea how to do this? I imagine some sort of introspection could be used, but I could be wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以考虑编写函数装饰器来检查第一个参数是否是列表。将装饰器应用于现有函数比修改函数要简单一些。
You can consider writing function decorator that checks if the first argument is a list. Applying decorator to existing functions is a bit simpler than modifying functions.
您可以使用 Yaroslav 发布的装饰器。
最小的例子:
You can use a Decorator as posted by Yaroslav.
Minimal example:
为什么不能使用第一个解决方案?
如果不可能,您仍然可以使用 func1(*tuple(func2(3, 4, 5))) (但您不需要)。
Why can't you use the first solution?
If that wasn't possible, you could still have used
func1(*tuple(func2(3, 4, 5)))
(but you don't need to).