*args, **kwargs的含义

* 的含义

数据中 * 的含义

1. 数值的乘法

a = 2
b = 3
a * b

运行结果:

6

2. 字符串的复制

string1 = "1, 2, 3, # "
string1 * 2

运行结果:

'1, 2, 3, # 1, 2, 3, # '

3. 字典的复制

list_name = [1, 2, 3, "abc"]
list_name * 2

运行结果:

[1, 2, 3, 'abc', 1, 2, 3, 'abc']
  1. 字典的复制
dic = {"a": 1, "b":2, "c":3}
dic * 2

出现错误(字典不能被复制)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-5bb5e1f2f925> in <module>
      1 dic = {"a": 1, "b":2, "c":3}
----> 2 dic * 2

TypeError: unsupported operand type(s) for *: 'dict' and 'int'

函数中 * 的含义

一个 * = *args

一个 * 代表 可以接受多个参数赋值,并放到元组中。

def func(*i):
    print(i)
    
func(1, "a", [1, 2, 3], {"a": 1, "b": 2}, (1, 2))

运行结果:

(1, 'a', [1, 2, 3], {'a': 1, 'b': 2}, (1, 2)) # 注意 : 整体是()元组类型

其中的 *i = *arg = 输入数据

两个 ** = **kwargs

可以传入多个参数, 并将参数转化成字典(也就是说:赋值的时候需要有键 和 值 或者是 形参 和 实参 , 两者缺一不可)

def funx(**i):
    print(i)
    
funx(1, 2, 3)

运行错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-09f1dfc704db> in <module>
      2     print(i)
      3 
----> 4 funx(1, 2, 3)

TypeError: funx() takes 0 positional arguments but 3 were given

原因: 只有一个参数,没有 键 : 值 或者 形参 = 实参


def funx(**i):
    print(i)
    
funx(a=1, b=2, c=3)

运行结果:

{'a': 1, 'b': 2, 'c': 3}

最后的存储形式是: 字典类型的数据。

注意嵌套的关系层次:

def funx(**i):
    print(i)
    
dic = {"a":1, "b":2}
funx(dic_name=dic, b=2, c=3)

运行结果:

{'dic_name': {'a': 1, 'b': 2}, 'b': 2, 'c': 3}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值