流暢的python和cookbook學習筆記(八),pythoncookbook

來源:互聯網
上載者:User

流暢的python和cookbook學習筆記(八),pythoncookbook
1.函數的預設參數必須不可變

  如果函數的預設參數為可變的對象,那麼預設參數在函數外被修改也會影響到函數本身的。

>>> def spam(a, b=None):  # b要為不可變參數,不能使用空列表 [] 等可變參數...     if b is None:...         b = []...

 

2.匿名函數

  1.想不出函數名時,或想要一種短小的操作,可以使用匿名函數

>>> sum = lambda x, y: x + y>>> sum(2, 3)5>>> def sum(x, y):   # 上面的匿名函數,相當於這個函數...     print(x + y)...>>> sum(3, 4)7

  2.匿名函數中的綁定變數

>>> x = 10>>> a = lambda y: x + y>>> x =20>>> b = lambda y: x +y>>> a(5)   # 發現不是期望的15,因為x被改變了25>>> b(5)25>>> x = 25>>> a = lambda y, x=x: x + y  # 在定義時綁定x,x就為局部變數了,不受x改變的影響>>> b = lambda y, x=x: x + y>>> a(5)30>>> b(5)20

 

聯繫我們

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