How the Python closure execution value is passed

Source: Internet
Author: User
This article mainly describes the Python closure execution value of the delivery method, in conjunction with the instance form of the python closure execution of the principle of transmission and implementation of the method, the code contains a more detailed comments easy to understand, the need for friends can refer to the next

In this paper, we analyze the delivery mode of Python closure execution value. Share to everyone for your reference, as follows:

There is an explanation of the problem and the problem in the code.

#!/usr/bin/python#coding:utf-8# judge whether a person passes, if the full score is 150, then 90 pass, if out of 100, then 60 Pass # Start doubts: When the fun function is finished, the corresponding Val value should disappear, but, # When the following code calls F (60) again (this f () function is the Fun_c () function) # but can print out Val value??? def Fun (val):  ' Val is getting the score '  # Print at this time to store Val's address print  ("%x"% ID (val))  def fun_c (passline):    ' Passline is the pass line '    if Val >= passline:      print ("through")    else:      print ("Failed")  return FUN_CF = Fun (89) # F is the Fun_c function # using __closure__ to print out the properties of the Fun_c () function, you can see that the ID value of the first element in F is the same as Val's ID value address # This means that if an external variable (enclosing variable) is referenced, This variable will be added to the function attribute # when looking again (i.e. F (60)), not in the code to find, but to the function properties to find the # that is, the above Fun_c attribute has Val value, is a tuple, can not change the print (f.__closure__) F (a) F = fun (in) F (90)

Operation Result:

12ee0b0 (<cell at 0x017b24b0:int object at 0x012ee0b0>,) failed through 12ee0b0

The role of closures:

1. Encapsulation of the Code

2. Code Reuse

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.