Smooth python and cookbook learning notes (8), pythoncookbook

Source: Internet
Author: User

Smooth python and cookbook learning notes (8), pythoncookbook
1. The default parameters of the function must be unchangeable.

If the default parameter of a function is a variable object, modification of the default parameter outside the function will also affect the function itself.

>>> Def spam (a, B = None): # variable parameters such as empty list [] cannot be used if B is an unchangeable parameter... if B is None :... B = []...

 

2. Anonymous Functions

1. You can use an anonymous function if you do not know the function name or want a short operation.

>>> Sum = lambda x, y: x + y >>>> sum (2, 3) 5 >>> def sum (x, y): # The above anonymous function, equivalent to this function... print (x + y)... >>> sum (3, 4) 7

2. bind variables to anonymous Functions

>>> X = 10 >>> a = lambda y: x + y >>>> x = 20 >>> B = lambda y: x + y> a (5) # found that not the expected 15, because x is changed by 25 >>> B (5) 25 >>> x = 25 >>> a = lambda y, x = x: x + y # bind x when defining, x is a local variable, not Affected by x changes> B = lambda y, x = x: x + y> a (5) 30> B (5) 20

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.