Python nesting functions

Source: Internet
Author: User

1. Nested function definitions

There is a special function in Python, which is defined inside the function, and functions such as those defined within other functions are called intrinsic functions, and the function of the inner function is called an external function. We can also define multi-layered nesting functions, which are intrinsic functions that define an intrinsic function. The definition of an intrinsic function is simple, as is the definition of Def, just inside a function, for example:

>>> var=90>>> def test ():d EF Nest (): Global Varprint (var) var+=1return Nest

>>> test () (90)


Note here that execution is test () (), not test (). Nest (), this is because test () returns a nest, and then executes Nest ().

2. Discuss the scope of nested functions

Intrinsic functions can use variables defined by external functions, such as:

def f ():d EF F1 (): X=3print ("Currently in function F1 (): x=", x) def f2 ():p rint ("Currently in function F2 (): x=", x) return F2return F1

>>> f () () ()

Currently in function F1 (): x= 3

Currently in function F2 (): x= 3

But

>>> def f ():

Def f1 ():

X=3

Print ("Currently in function F1 (): x=", X)

def f2 ():

X+=5

Print ("Currently in function F2 (): x=", X)

return F2

Return F1

>>> f () () ()

Currently in function F1 (): x= 3

Traceback (most recent):

File "<pyshell#47>", line 1, in <module>

F () () ()

File "<pyshell#46>", line 6, in F2

X+=5

unboundlocalerror:local variable ' x ' referenced before assignment



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.