Python rookie advance----closures

Source: Internet
Author: User
Tags function definition

Introduction

Closure (closure) is an important grammatical structure of functional programming. Functional programming is a programming paradigm (both procedural programming and object-oriented programming are also programming paradigms). In process-oriented programming, we have seen functions (function), and in object-oriented programming we have seen objects (object). The fundamental purpose of functions and objects is to organize the code in some logical way and to improve the code's repeatability (reusability). closures are also a structure for organizing code, which also improves the reusable nature of code.
Different languages implement closures in different ways. Python is based on a function object and provides support for the syntactic structure of closures (we have seen Python use objects for some special syntax in special methods and multiple paradigms). Python everything is object, function This syntax structure is also an object. In a function object, we use a function object like a normal object, such as changing the name of a function object, or passing a function object as a parameter.

Scope of Function objectLike other objects, a function object has its own scope, that is, the scope of the function object. A function object is defined with a DEF statement, and the scope of the function object is the same as the level at which the def resides. For example, the following code, which is defined within the membership scope of the LINE_CONF function, can only be called within the LINE_CONF's membership range.

Def line_conf ():    def line (x):        return 2*x+1    print (line (5))   # Smooth execution of line_conf () print (line (5))       # Error!  

Similarly, if you use lambda to define a function, the scope of the function object is the same as the level at which the Lambda resides.

Closed PackageA function is an object, so it can be returned as a result of a function. In Python, the so-called closure is a function object that contains the value of an environment variable.

Def line_conf (A, B):    def line (x):        return ax + b    return lineline1 = line_conf (1, 1) line2 = line_conf (4, 5) print (Line1 (5), line2 (5))
In this example, the function line and the environment variable A, a and B constitute the closure. When we created the closure, we explained the values of the two environment variables through the line_conf parameter, a and B, so that we determined the final form of the function (y = x + 1 and y = 4x + 5). We only need to change the parameter, a, B, we can get a different line expression function. Thus, we can see that closures also have the effect of improving code reusability.
Without closures, we need to explain a,b,x each time we create a line function. In this way, we need more parameter passing and less portability of the code. With closures, we actually created theFunctional。 The line function defines a broad-sense function. Some aspects of this function have been determined (must be straight lines), but others (such as the A and B parameters are pending). We then determine the final function in the form of a closure, based on the parameters passed by line_conf.
@ modifier

The ' @ ' symbol used as a function modifier is a new addition to python2.4, and the modifier must appear on the previous line of the function definition and is not allowed on the same line as the function definition. That is to say @a def f (): is illegal. Functions can be decorated only within a module or class definition layer, and no modification of a class is allowed. a modifier is a function that makes the modified function a parameter and returns a modified function with the same name or other callable object.

@dec2  @dec1  def func (arg1, Arg2, ...):      Pass  
Equivalent to

def func (arg1, Arg2, ...):      pass  func = dec2 (DEC1 (func))  

Practical Small Example
def makebold (FN):    def wrapped ():        return "<b>" + fn () + "</b>"    return wrappeddef makeitalic (FN):    def wrapped ():        return "<i>" + fn () + "</i>"    return wrapped@makebold@makeitalicdef Hello ():    
Output results
<b><i>hello world</i></b>



Previous: Python rookie promotion----special attribute collation

Next Talk:

If you have any questions, welcome to my public question ~

Python rookie advance----closures

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.