python 星号

Posted by bower on August 10, 2009
python

分享给你的朋友->bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark

F(*arg1)
它以一个*加上形参名的方式来表示这个函数的实参个数不定,可能为0个也可能为n个。注意一点是,不管有多少个,在函数内部都被存放在以形参名为标识符的tuple中。
>>> def a(*x):
if len(x)==0:
print ‘None’
else:
print x
>>> a(1)
(1,)        #存放在元组中
>>> a()
None
>>> a(1,2,3)
(1, 2, 3)
>>> a(m=1,y=2,z=3)

Traceback (most recent call last):
File “<pyshell#16>”, line 1, in -toplevel-
a(m=1,y=2,z=3)
TypeError: a() got an unexpected keyword argument ‘m’

.F(**arg1)
形参名前加俩个*表示,参数在函数内部将被存放在以形式名为标识符的dictionary中,这时调用函数的方法则需要采用arg1=value1,arg2=value2这样的形式。
>>> def a(**x):
if len(x)==0:
print ‘None’
else:
print x
>>> a()
None
>>> a(x=1,y=2)
{‘y’: 2, ‘x’: 1}      #存放在字典中
>>> a(1,2)            #这种调用则报错

Traceback (most recent call last):
File “<pyshell#25>”, line 1, in -toplevel-
a(1,2)
TypeError: a() takes exactly 0 arguments (2 given)

分享到:人人网开心网腾讯微博新浪微博豆瓣分享腾讯空间百度搜藏腾讯书签

分享给你的朋友->bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word