缺省參數,不定長參數

缺省參數:

>>> def printinfo(name, age=35, sex): ...     print name ...   File "<stdin>", line 1 SyntaxError: non-default argument follows default argument

帶有默認值的參數必定要位於參數列表的最後面。python

 

def printinfo( name, age = 35 ):    # 打印任何傳入的字符串    print "Name: ", name    print "Age ", age  # 調用printinfo函數 printinfo(name="miki" ) printinfo( age=9,name="miki" )

缺省參數的值若是沒有傳入,則被認爲是默認值。下例會打印默認的age,若是age沒有被傳入函數

 

不定長參數:spa

有時可能須要一個函數能處理比當初聲明時更多的參數。這些參數叫作不定長參數,聲明時不會命名。code

基本語法以下:加了星號(*)的變量args會存放全部未命名的變量參數,args爲元組;而加**的變量kwargs會存放命名參數,即形如key=value的參數, kwargs爲字典。blog

>>> def fun(a, b, *args, **kwargs): ...     """可變參數演示示例""" ...     print "a =", a ...     print "b =", b ...     print "args =", args ...     print "kwargs: " ...     for key, value in kwargs.items(): ...         print key, "=", value ... >>> fun(1, 2, 3, 4, 5, m=6, n=7, p=8)  # 注意傳遞的參數對應 a = 1 b = 2 args = (3, 4, 5) kwargs:  p = 8 m = 6 n = 7 >>> >>> >>> >>> c = (3, 4, 5) >>> d = {"m":6, "n":7, "p":8} >>> fun(1, 2, *c, **d)    # 注意元組與字典的傳參方式 a = 1 b = 2 args = (3, 4, 5) kwargs:  p = 8 m = 6 n = 7 >>> >>> >>> >>> fun(1, 2, c, d) # 注意不加星號與上面的區別 a = 1 b = 2 args = ((3, 4, 5), {'p': 8, 'm': 6, 'n': 7}) kwargs: >>> >>>
相關文章
相關標籤/搜索