请转到http://iMath.cnblogs.com

■■■■■■■■■■本博客打算放弃,请转到http://iMath.cnblogs.com

Collecting Parameters and Distribute Parameters

################################   *   ###############################

The star in front of the parameter puts all the values into the same tuple. 

def print_params_2(title, *params):

    print title

    print params


>>> print_params_2('Params:', 1, 2, 3)

Params:

(1, 2, 3)

################################   **   ##############################

 ** “gathering” operator for keyword arguments.

def print_params_3(**params):

    print params


>>> print_params_3(x=1, y=2, z=3)

{'z': 3, 'x': 1, 'y': 2}


################################ more practice ######################

def print_params_4(x, y, z=3, *pospar, **keypar):

    print x, y, z

    print pospar

    print keypar



>>> print_params_4(1, 2, 3, 5, 6, 7, foo=1, bar=2)

1 2 3

(5, 6, 7)

{'foo': 1, 'bar': 2}

>>> print_params_4(1, 2)

1 2 3

()

{}

###################################################################


def add(x, y): return x + y

params = (1, 2)


>>> add(*params)

3



def hello_3(greeting='Hello', name='world'):

    print '%s, %s!' % (greeting, name)


>>> params = {'name': 'Sir Robin', 'greeting': 'Well met'}

>>> hello_3(**params)

Well met, Sir Robin!


The stars are really useful only if you use them either when defining a function (to allw a varying number of arguments) or when calling a function (to “splice in” a dictionary or a sequence).





评论

© 请转到http://iMath.cnblogs.com | Powered by LOFTER