python 传参的问题

** 将字典对象处理对应的字典对象


>>> d = {'a': 3, 'b': 2, 'c': 3}

>>> l = [1,2,3,4]

>>> class Func(object):
...     def __init__(self, **kwargs):
...         print kwargs

... 


>>> Func(d)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    Func(d)
TypeError: __init__() takes exactly 1 argument (2 given)


>>> Func(*d)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    Func(*d)
TypeError: __init__() takes exactly 1 argument (4 given)


>>> Func(**d)
{'a': 3, 'c': 3, 'b': 2} 


>>> Func(l)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    Func(l)
TypeError: __init__() takes exactly 1 argument (2 given)


>>> Func(**l)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    Func(**l)
TypeError: type object argument after ** must be a mapping, not list


*将序列中的元素处理成对应的元组对象 


>>> class Func(object):
...     def __init__(self, *kwargs):
...         print kwargs, type(kwargs)
...         
...     
... 
>>> Func(d)
({'a': 3, 'c': 3, 'b': 2},) <type 'tuple'>
<__console__.Func object at 0x2c38450>
>>> Func(*d)
('a', 'c', 'b') <type 'tuple'> 
<__console__.Func object at 0x2ad6e10>
>>> Func(**d)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    Func(**d)
TypeError: __init__() got an unexpected keyword argument 'a'
>>> Func(l)
([1, 2, 3, 4],) <type 'tuple'> 
<__console__.Func object at 0x2a81e10>
>>> Func(*l)
(1, 2, 3, 4) <type 'tuple'>
<__console__.Func object at 0x2c50790>
>>> Func(**l)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    Func(**l)
TypeError: type object argument after ** must be a mapping, not list

>>> s='1234'
>>> Func(*s)
('1', '2', '3', '4') <type 'tuple'> xxxxxxxx
<__console__.Func object at 0x2c52e90>



未处理时只表示对象自身


>>> class Func(object):
...     def __init__(self, kwargs):
...         print kwargs, type(kwargs)
...         
...     
... 
>>> Func(d)
{'a': 3, 'c': 3, 'b': 2} <type 'dict'>
<__console__.Func object at 0x2ae4210>
>>> Func(*d)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    Func(*d)
TypeError: __init__() takes exactly 2 arguments (4 given)
>>> Func(**d)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    Func(**d)
TypeError: __init__() got an unexpected keyword argument 'a'
>>> Func(l)
[1, 2, 3, 4] <type 'list'>
<__console__.Func object at 0x2822350>
>>> Func(*l)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    Func(*l)
TypeError: __init__() takes exactly 2 arguments (5 given)
>>> Func(**l)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    Func(**l)
TypeError: type object argument after ** must be a mapping, not list

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值