*params、**params: Collecting Parameters and Distribute Parameters

博客主要介绍了Python中函数参数的聚合与分发操作。通过*和**运算符,可将参数聚合为元组或字典,如定义函数时使用*params、**params;也能在调用函数时进行分发,将元组或字典拆分为参数传递给函数,展示了相关代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

()

{}

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

This is more or less the opposite of what we did previously. Instead of gathering the parameters, we want to distribute them. This is simply done by using the * operator at the “other end”—that is, when calling the function rather than when defining it.

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)

 

This works with parts of a parameter list, too, as long as the expanded part is last. You can use the same technique with dictionaries, using the ** operator.

>>> 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).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值