Python functional Programming--return function

Source: Internet
Author: User

1.1   return function1.1.1   function as return value

>>> def lazy_sum (*args): # variable parameter

... def sum ():

... Ax = 0

... for i in args: # calling parameters of an external function

.... Ax = ax + I

.... return ax

... return sum-- a function returned here

...

>>>

>>>

>>> lazy_sum (1, 3, 5, 7)

<function Lazy_sum.<locals>.sum at0x2b8091d87268>

>>> lazy_sum (1,3, 5, 7) ()

16

>>> F =lazy_sum (1, 3, 5, 7)

>>> F

<function Lazy_sum.<locals>.sum at0x2b8091d87268>

>>> F ()

16

Note: When we call lazy_sum () , each call will return a new function , even if the same parameters are passed in

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

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

>>> F1 = = F2

False

1.1.2   Closed Package

Look at the closure problem.

>>> def count ():

... fs = []

... for i in range (1, 4):

... def f ():

... return I*i

... fs.append (f)

... return FS

...

>>> F1, F2, F3 = count ()-- variable i all refer to 3

>>>

>>> F1

<function COUNT.<LOCALS>.F at0x2b8091d87488>

>>> F1 ()

9

>>> F2 ()

9

>>> F3 ()

9

the back function references the variable i, but it is not executed immediately. when all 3 functions return, they refer to the variable i has become 3, so the final result is 9.

Rewrite code

>>> def count ():

... def f (j):

... return lambda:j*j-- reference J variable,lambda anonymous function without parameter

... fs = []

... for i in range (1, 4):

... fs.append (f (i))

... return FS

>>> F1 ()

1

>>> F2 ()

4

>>> F3 ()

9


This article is from the "90SirDB" blog, be sure to keep this source http://90sirdb.blog.51cto.com/8713279/1820912

Python Functional Programming--return function

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.