* args,** kwargs与使用tuple和dict调用有什么区别? [英] What is the difference in *args, **kwargs vs calling with tuple and dict?

查看:156
本文介绍了* args,** kwargs与使用tuple和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)

我对两者都可以做同样的事情,除了后者在创建tupledictionary方面有一个怪异的约定.但是基本上有区别吗?我可以解决相同的计算问题,因为dicttuple可以帮我解决这个问题吗?

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:虽然我同意这是

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?

推荐答案

argskwargs只是名称.
真正重要的是***.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆