What is a python return function? (Instance parsing)

Source: Internet
Author: User
Tags closure
In the following article, let's look at what is a return function in Python. Learn about the Python return function, well, don't talk about it. Let's go into the following article.

The Python function as the return value:

Higher-order functions can also return a function as a result value, in addition to the ability to accept functions as parameters.

Let's implement the summation of a mutable parameter. In general, the function of summing is defined like this:

def calc_sum (*args):    ax = 0 for    n in args: Ax        = ax + n    return ax

But what if you don't need to sum it right away, but in the later code, and then calculate it as needed? Instead of returning the result of a sum, you can return a function that sums:

def lazy_sum (*args):    def sum ():        ax = 0 for        n in args:            ax = ax + n        return ax    return sum

When we call Lazy_sum (), we return the SUM function instead of summing the result:

>>> f = lazy_sum (1, 3, 5, 7, 9) >>> f<function lazy_sum.<locals>.sum at 0x101c6ed90>

The result of summing is actually computed when the function f is called:

>>> F () 25

In this example, we define the function sum in the function lazy_sum, and the inner function sum can refer to the arguments and local variables of the external function lazy_sum, and when Lazy_sum returns the function sum, the relevant parameters and variables are stored in the returned function, which is called " The program structure of the closure (Closure) has great power.

Note again that when we call Lazy_sum (), each call returns a new function, even if the same parameter is passed in:

>>> f1 = lazy_sum (1, 3, 5, 7, 9) >>> F2 = lazy_sum (1, 3, 5, 7, 9) >>> F1==f2false

The invocation results of F1 () and F2 () do not affect each other.

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.