* args,** kwargs与使用tuple和dict调用有什么区别? [英] What is the difference in *args, **kwargs vs calling with tuple and dict?
问题描述
这是一个基本问题.这样做有什么区别吗
This is a basic question. Is there a difference in doing
def foo(*args, **kwargs):
"""standard function that accepts variable length."""
# do something
foo(v1...vn, nv1=nv1...nvn=nvn)
def foo(arg, kwargs):
"""convention, call with tuple and dict."""
# do something
mytuple = (v1, ..vn)
mydict = {nv1=nv1, ...nvn=nvn}
foo(mytuple, mydict)
我对两者都可以做同样的事情,除了后者在创建tuple
和dictionary
方面有一个怪异的约定.但是基本上有区别吗?我可以解决相同的计算问题,因为dict
和tuple
可以帮我解决这个问题吗?
I could do the same thing with both, except that the later has a weird convention of creating a tuple
and dictionary
. But basically is there a difference? I can solve the same computational problem of handling infinite things because dict
and tuple
can take care of that for me anyway?
这更多是Python的惯用法吗,也就是说,对于您无论如何要做的事情来说,它都是一个很好的 Syntactic Sugar ?即function
将为您解决这个问题!
Is this more of an idiomatic part of Python i.e a good Syntactic Sugar for things that you do anyway? I.e function
is going to handle this for you!
PS: Not sure of so many downvotes though I agree this is a copy of Why use packed *args/**kwargs instead of passing list/dict? and probably it should be corrected in the duplicate information. And that question has recieved upvotes. So am I being downvotes for not being able to find that?
推荐答案
args
和kwargs
只是名称.
真正重要的是*
和**
.
args
and kwargs
are just names.
What really matters here is the *
and **
.
在第二个示例中,您只能使用带有2个参数的函数来调用函数,而在第一个示例中,您只能使用基本上无限的参数来调用函数.
In your second example you can only call the function with 2 arguments, against the first example where you can call the function with basically infinite arguments.
这篇关于* args,** kwargs与使用tuple和dict调用有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!