python中變長參數的用法舉例?__python

來源:互聯網
上載者:User

慎用變長參數
python支援可變長度的參數列表,可以通過*arg, **kwargs這兩個特殊文法來實現。以下為變長參數使用的例子:
* 使用*args 來實現可變參數列表: *args用接受
一個封裝為元組形式的參數列表來傳遞非關鍵字參數,參數個數可以隨意。

def SumFun(*args):    result = 0    for x in args[0:]:      result += x    return resultprint SumFun(2, 4)print SumFun(1,2,3,4,5)print SumFun()
使用**kwargs接收字典形式的關鍵字參數列表,其中字典的索引值對分別表示不可變參數的參數名和值。
def category_table(**kwargs):    for name, value in kwargs.items():        print '{0} is a kind of {1}'.format(name, value)category_table(apple='fruit', carrot='vegetable')category_table(BMW = 'Car')
一個函數中同時定義了普通參數,預設參數,以及上述兩種形式的可變參數,那麼使用方式又會是怎麼樣的呢。
def set_axis(x, y xlabel='x', ylable='y', *args, **kwargs):    pass
在下列情境下適合使用可變參數
def mydecorator(fun):    def new(*args, **kwargs):      return fun(*args, **kwargs)    return new

如果參數數目不確定,可以考慮使用變長參數。

用來實現函數的多態或者在繼承情況下子類需要調用父類的某些方法的時候。

class A(object):    def somefun(self, p1, p2):        passclass B(A):    def myfun(self, p3, *args, **kwargs):        super(B, self).somefun(*args, **kwargs)

本文摘自《編寫高品質代碼 改善python程式的91個建議》

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.