The return function of the advanced Python

Source: Internet
Author: User

<title>return function</title> return function

The Python function returns not only data types such as int, str, list, dict, but also functions.
To give a chestnut: Define a function f () and let it return a function g

1. def F():
2. Print ' call F () ... '
3. #定义函数g
4. def G():
5. Print ' Call g (... ')
6. #返回函数g
7. returnG

Call the function f, and we'll get a function of the F return:

1.>>> x = f()   # 调用f()
2.call f()...
3.>>> x # 变量x是f()返回的函数:
4.0x1037bf320>
5.>>> x() # x指向函数,因此可以调用
6.call g()... # 调用x()就是执行g()函数定义的代码

Note that the return function and return value are distinguished:

1.def myabs():
2. return abs # 返回函数
3.def myabs2(x):
4. return abs(x) # 返回函数调用的结果,返回值是一个数值

The return function can delay execution of some computations. For example, if you define a normal sum function:

1.def calc_sum(lst):
2. return sum(lst)

When the Calc_sum () function is called, the result is calculated and obtained immediately:

1.>>> calc_sum([1234])
2.10

However, if you return a function, you can "defer calculation":

1.def calc_sum(lst):
2. def lazy_sum():
3. return sum(lst)
4. return lazy_sum

The call to Calc_sum () does not calculate the result, but instead returns the function:

1.>>> f = calc_sum([1234])
2.>>> f
3.0x1037bfaa0>

The result is calculated when a call is made to the returned function:

1.f()
2.10

Since the function can be returned, we can decide in the subsequent code whether or not to invoke the function.

For example, to write a function Calc_prod (LST), it receives a list, returns a function, and returns a function that calculates the product of the parameter.

1. def calc_prod(LST):
2. def prob():
3. def F(x, y):
4. returnX*y
5. returnReduce (F,LST,1)
6. returnProb
7.
8.f = Calc_prod ([1,2,3,4])
9.PrintF ()

The return function of the advanced Python

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.