Python學習——函數

來源:互聯網
上載者:User

標籤:def   可變參   集合   log   named   函數   學習   pytho   武漢   

Python的函數部分知識與其他語言差不多,唯獨參數這塊,有點不好理解。

1.預設參數

def f_default_parameters(a,b,c=1):    print(a,b,c)f_default_parameters(1,2,3)f_default_parameters(1,2,c=3)

2.可變參數(內部將參數組裝成tuple)

def f_variable_parameters(*args):    print(args)f_variable_parameters(1,2,3)f_variable_parameters(*[1,2,3])  #將集合轉換成可變參數f_variable_parameters(*(1,2,3))  #將元群組轉換成可變參數f_variable_parameters()

3.關鍵字參數(函數內部將參數組裝成dict)

def f_keyword_parameters(**kv):    print(kv)f_keyword_parameters(name=‘owen‘,age=3)f_keyword_parameters(**{‘name‘:‘owen‘,‘age‘:3})
4.命名關鍵字參數(限制關鍵字參數)
def f_named_keyword_parameters(*,city,address=‘hubei of china‘):    print(city,address)f_named_keyword_parameters(city=‘wuhan‘)f_named_keyword_parameters(city=‘wuhan‘,address=‘hubei of china‘)
5.組合
#如果已經有了可變參數,則後面的命名關鍵字參數則不需要*分隔字元了def f(*args, city=‘武漢‘,address):    print(args,city,address)f(1,2,city=‘wuhan‘,address=‘hubei of china‘)
def f(*args, city=‘武漢‘,**kv):    print(args,city,kv)f(1,2,city=‘wuhan‘,address=‘hubei of china‘)
#對於任意函數,都可以通過類似func(*args,**kw)的形式調用它,無論它的參數是如何定義的def f(*args, **kv):    print(args,kv)f(1,2,city=‘wuhan‘,address=‘hubei of china‘)




Python學習——函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.