Python中的“*”和“**”

 1.接受任意长度形参,组成turple

def function(*args):
    # type(args)==turple
    # args==(1, 2, 3, 4)
    print(args)
    ant=0
    for i in range(len(args)):
        ant+=args[i]
    return ant

print(function(1,2,3,4))  # 10

 2.接受任意长度形参,组成dict

def function(**args):
    # type(args)==<class'dict'>
    print(type(args))
    # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
    print(args)
    ants = 0
    for key in args:
        ants+=args[key]
    return ants
 
print(function(a=1,b=2,c=3,d=4))   # 10

# 注意这种方法是错误的
print( function({"a":1,"b":2,"c":3,"d":4}) )
# TypeError: function() takes 0 positional arguments but 1 was given
def my_function(**kwargs):
    # {'a': 1, 'b': 2}
    print(kwargs)

my_dict = {'a': 1, 'b': 2}
my_function(**my_dict)

 3. 拿出参数

在list中 

def sample_function(a, b, c):
    print(a, b, c)

list = [1, 2, 3]

sample_function(*list)


list2=[10,list,20]
list3=[10,*list,20]
# [10, [1, 2, 3], 20]
print(list2)
# [10, 1, 2, 3, 20]
print(list3)

在turple中 

def sample_function(a, b, c):
    print(a, b, c)

list = (1, 2, 3)

sample_function(*list)

list2=(10,list,20)
list3=(10,*list,20)
# (10, (1, 2, 3), 20)
print(list2)
# (10, 1, 2, 3, 20)
print(list3)

4.函数传参对号入座

def test(a, b):
    print(f"a={a}, b={b}")

d = {'b': 200, 'a':30}
test(**d)

参数和形参名称不对应,报错 

def test(c,d):
    print(c," ",d)
d = {'b': 100, 'a':10}
test(**d)
"""
File "d:\WorkSpace\MachineLearning\d2l_learn\mainTest2.py", line 4, in <module>
    test(**d)
TypeError: test() got an unexpected keyword argument 'b'
"""

题外话:看到*args和**kwds既不害怕了

class Person(object):
    def __init__(self) -> None:
        pass
    def __call__(self, *args: Any, **kwds: Any) -> Any:
        pass
    def __new__(cls) :
        pass

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值