Article From:https://www.cnblogs.com/geeklove01/p/9122303.html

According to document (https://docs.python.org/2/tutorial/controlflow.html#more-on-defining-functions)

Three methods are introduced.

1 Default Argument Values 

The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow

It is simpler to assign a default value to the parameters in each method.

The default values are evaluated(Assignment)at the point of function definition in the defining scope, so that

i = 5

def f(arg=i):
    print arg

i = 6
f()

will print 5.

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

def f(a, L=[]):
    L.append(a)
    return L

print f(1)
print f(2)
print f(3)

this will print:

[1]
[1, 2]
[1, 2, 3]

If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

 

2 Arbitrary Argument Lists

When using *args, the incoming parameters, packtupleTo deal with:

def foo(*args):
  for a in args:
    print a
  print 'end of call'

lst = [1,2,3]
foo(lst)    
foo(*lst)

#output:
[1, 2, 3]
end of call
1
2
3
end of call

 

3 Keyword Arguments

When using **kw, all incoming keyword arguments will be pack to dict processing:

When a final formal parameter of the form **name is present, it receives a dictionary (see Mapping Types — dict) containing all keyword arguments except for those corresponding to a formal parameter.

The explanation of this sentence:

def bar(name='Jack', age=21, **kw):
  print kw

bar(a=1, b=2)  # {'a': 1, 'b': 2}
bar(name='Lucy', job='doctor') # {'job': 'doctor'}

 

stackoverflow(https://stackoverflow.com/questions/33542959/why-use-packed-args-kwargs-instead-of-passing-list-dict)The summary of * * * * * * * application scenarios:

*args/**kwargs has its advantages, generally in cases where you want to be able to pass in an unpacked data structure, while retaining the ability to work with packed ones.

Of course, if you expect the function to always be passed multiple arguments contained within a data structure, as sum() and str.join() do, it might make more sense to leave out the *syntax.

 

The interpretation of Unpacking Argument Lists:

The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments.

Give an example:

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

In the same fashion, dictionaries can deliver keyword arguments with the **-operator:

>>> def parrot(voltage, state='a stiff', action='voom'):
...     print "-- This parrot wouldn't", action,
...     print "if you put", voltage, "volts through it.",
...     print "E's", state, "!"
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

 

 

 

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *