无他,唯手熟尔!

*args and **kwargs

Use *args and **kwargs just for convenience and don’t force them.

You can use *args when you are not sure how many parameters you will pass in your function. For example, it can pass any number of arguments:

def print_everything(*args):
For count, thing in enumerate(args):
… print '{0}. {1}'.format(count, thing)

print_everything('apple', 'banana', 'cabbage')
  1. apple
    Banana
  2. cabbage
    Similarly, **kwargs allows you to use parameter names that are not defined beforehand:
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 also mix them. Named parameters first get the parameter values ​​and then all other parameters are passed to *args and **kwargs. The named parameters are at the front of the list. For example:

Def table_things(titlestring, **kwargs)
*args and **kwargs can be in the definition of a function at the same time, but *args must be in front of **kwargs.

You can also use the * and ** syntax when calling functions. 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, it can pass every item of the list (or tuple) and unpack them. Note that it must match the parameters in the function. Of course, you can also call the function definition or function. Use *.

赞(0) 打赏
未经允许不得转载:沙の志 » *args and **kwargs

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

沙の志