使用* args和** kwargs [重复]

本文翻译自:Use of *args and **kwargs [duplicate]

This question already has answers here : 这个问题已经在这里有了答案
Closed 6 years ago . 6年前关闭。

So I have difficulty with the concept of *args and **kwargs . 所以我很难理解*args**kwargs的概念。

So far I have learned that: 到目前为止,我已经了解到:

  • *args = list of arguments - as positional arguments *args =参数列表-作为位置参数
  • **kwargs = dictionary - whose keys become separate keyword arguments and the values become values of these arguments. **kwargs =字典-其键成为单独的关键字参数,而值则成为这些参数的值。

I don't understand what programming task this would be helpful for. 我不知道这对您有什么帮助。

Maybe: 也许:

I think to enter lists and dictionaries as arguments of a function AND at the same time as a wildcard, so I can pass ANY argument? 我认为要输入列表和字典作为函数的参数,并与通配符同时输入,因此我可以传递ANY参数吗?

Is there a simple example to explain how *args and **kwargs are used? 有一个简单的示例来说明如何使用*args**kwargs吗?

Also the tutorial I found used just the "*" and a variable name. 我发现的教程也只使用了“ *”和一个变量名。

Are *args and **kwargs just placeholders or do you use exactly *args and **kwargs in the code? *args**kwargs只是占位符还是在代码中使用了*args**kwargs


#1楼

参考:https://stackoom.com/question/EF9P/使用-args和-kwargs-重复


#2楼

The names *args and **kwargs or **kw are purely by convention. 名称*args**kwargs**kw完全是约定俗成的。 It makes it easier for us to read each other's code 它使我们更容易阅读彼此的代码

One place it is handy is when using the struct module 一个方便的地方是使用struct模块时

struct.unpack() returns a tuple whereas struct.pack() uses a variable number of arguments. struct.unpack()返回一个元组,而struct.pack()使用可变数量的参数。 When manipulating data it is convenient to be able to pass a tuple to struck.pack() eg. 当处理数据时,能够将元组传递给struck.pack()很方便。

tuple_of_data = struct.unpack(format_str, data)
... manipulate the data
new_data = struct.pack(format_str, *tuple_of_data)

without this ability you would be forced to write 没有这种能力,你将不得不写

new_data = struct.pack(format_str, tuple_of_data[0], tuple_of_data[1], tuple_of_data[2],...)

which also means the if the format_str changes and the size of the tuple changes, I'll have to go back and edit that really long line 这也意味着,如果format_str更改并且元组的大小更改,我将不得不返回并编辑该长行


#3楼

The syntax is the * and ** . 语法是*** The names *args and **kwargs are only by convention but there's no hard requirement to use them. 名称*args**kwargs仅是约定俗成的,但使用它们并没有硬性要求。

You would use *args when you're not sure how many arguments might be passed to your function, ie it allows you pass an arbitrary number of arguments to your function. 当您不确定可以向函数传递多少个参数时,可以使用*args ,即,它允许您将任意数量的参数传递给函数。 For example: 例如:

>>> def print_everything(*args):
        for count, thing in enumerate(args):
...         print( '{0}. {1}'.format(count, thing))
...
>>> print_everything('apple', 'banana', 'cabbage')
0. apple
1. banana
2. cabbage

Similarly, **kwargs allows you to handle named arguments that you have not defined in advance: 同样, **kwargs允许您处理尚未预先定义的命名参数:

>>> def table_things(**kwargs):
...     for name, value in kwargs.items():
...         print( '{0} = {1}'.format(name, value))
...
>>> table_things(apple = 'fruit', cabbage = 'vegetable')
cabbage = vegetable
apple = fruit

You can use these along with named arguments too. 您也可以将它们与命名参数一起使用。 The explicit arguments get values first and then everything else is passed to *args and **kwargs . 显式参数首先获取值,然后将其他所有*args传递给*args**kwargs The named arguments come first in the list. 命名参数在列表中排在第一位。 For example: 例如:

def table_things(titlestring, **kwargs)

You can also use both in the same function definition but *args must occur before **kwargs . 您也可以在相同的函数定义中使用两者,但是*args必须在**kwargs之前出现。

You can also use the * and ** syntax when calling a function. 调用函数时,也可以使用***语法。 For example: 例如:

>>> def print_three_things(a, b, c):
...     print( 'a = {0}, b = {1}, c = {2}'.format(a,b,c))
...
>>> mylist = ['aardvark', 'baboon', 'cat']
>>> print_three_things(*mylist)
a = aardvark, b = baboon, c = cat

As you can see in this case it takes the list (or tuple) of items and unpacks it. 如您所见,在这种情况下,它将获取项目列表(或元组)并将其解包。 By this it matches them to the arguments in the function. 这样,就可以将它们与函数中的参数匹配。 Of course, you could have a * both in the function definition and in the function call. 当然,在函数定义和函数调用中都可以带有*


#4楼

One place where the use of *args and **kwargs is quite useful is for subclassing. 使用*args**kwargs非常有用的一个地方是子类化。

class Foo(object):
    def __init__(self, value1, value2):
        # do something with the values
        print value1, value2

class MyFoo(Foo):
    def __init__(self, *args, **kwargs):
        # do something else, don't care about the args
        print 'myfoo'
        super(MyFoo, self).__init__(*args, **kwargs)

This way you can extend the behaviour of the Foo class, without having to know too much about Foo. 这样,您可以扩展Foo类的行为,而不必对Foo了解太多。 This can be quite convenient if you are programming to an API which might change. 如果您正在编程可能会更改的API,这将非常方便。 MyFoo just passes all arguments to the Foo class. MyFoo只是将所有参数传递给Foo类。


#5楼

*args and **kwargs are special-magic features of Python. * args和** kwargs是Python的特殊魔术功能。 Think of a function that could have an unknown number of arguments. 考虑一个可能具有未知数量参数的函数。 For example, for whatever reasons, you want to have function that sums an unknown number of numbers (and you don't want to use the built-in sum function). 例如,无论出于何种原因,您都希望具有对未知数量的数字求和的函数(并且您不想使用内置的sum函数)。 So you write this function: 所以你写这个函数:

def sumFunction(*args):
  result = 0
  for x in args:
    result += x
  return result

and use it like: sumFunction(3,4,6,3,6,8,9). 并像这样使用它:sumFunction(3,4,6,3,6,8,9)。

**kwargs has a diffrent function. ** kwargs具有不同的功能。 With **kwargs you can give arbitrary keyword arguments to a function and you can access them as a dictonary. 使用** kwargs可以为函数提供任意关键字参数,并且可以将它们作为字典使用。

def someFunction(**kwargs):
  if 'text' in kwargs:
    print kwargs['text']

Calling someFunction(text="foo") will print foo. 调用someFunction(text =“ foo”)将打印foo。


#6楼

Just imagine you have a function but you don't want to restrict the number of parameter it takes. 试想一下,如果您有一个函数,但是不想限制它需要的参数数量。 Example: 例:

>>> import operator
>>> def multiply(*args):
...  return reduce(operator.mul, args)

Then you use this function like: 然后,您可以使用以下功能:

>>> multiply(1,2,3)
6

or

>>> numbers = [1,2,3]
>>> multiply(*numbers)
6
发布了0 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/p15097962069/article/details/105239266
今日推荐