[Python Reading] cookbook-20.1 gets a new default value in function calls

Source: Internet
Author: User

I never saw the decorator. Today I flipped through the cookbook and read it for a while.

20.1 obtain new default values in function calls

Task: After the def statement of the function is executed, Python calculates the default value for the optional parameter of the function, but only once.

For some functions, each time you want to call a function, the default value is calculated.

CodeAs follows:

Import copydef freshdefaults (F): "An F-encapsulated decorator that keeps its default value new during calls" fdefaults = f. func_defaults def refresher (* ARGs, ** kwds): f. func_defaults = copy. deepcopy (fdefaults) return F (* ARGs, ** kwds) return refresher # @ freshdefaultsdef packitem (item, PKG = []): PKG. append (item) return pkg a = packitem (1) B = packitem (2) print ID (a), a print ID (B ), B ''' result of using the decorator 47262256 [1] 47263336 [2] ''' result of not using the decorator 45811952 [1, 2] 45811952 [1, 2] '''

At first, I really didn't understand what it meant. Later, after debugging, I understood some details. The result is obvious, that is, the scope of the default value, or the problems of deep copy and shallow copy.

Is the debugging information when B is about to get the value

Related Article

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.