Nested Python function instances

Source: Internet
Author: User

Nested Python function instances

Functions in Python can be passed as parameters, and can be assigned to other variables (similar to Javascript, or function pointers in C/C ++ );

Similar to Javascript, Python supports function nesting. The application mode of Javascript nested functions is applicable to Python;
Copy codeThe Code is as follows:
>>> Def multiplier (factor ):
... Def multiple (number ):
... Return number * factor
... Return multiple
...
>>>
>>> Multiplier (3) (3)
9
>>> Multiplier (4) (3)

The closure feature is closely related to nested functions. For example:

Copy codeThe Code is as follows:
>>> Def test ():
... A = {'name': 'wyj '}
... Def f ():
... Return a ['name']
... Return f
...
>>> Def test ():
... A = {'name': 'wyj '}
... Def f ():
... Return a ['name']
... Return a, f
...
>>> A, f = test ()
>>> F ()
'Wyj'
>>> A ['name'] = 'ljq'
>>> F ()
'Ljq'


Nested python Functions

Because the last return nested sentence.

Tester () automatically calls its return value, and the return value is nested, that is, def nested (), so the print statement in it is executed naturally.
You can try to change return nested to another one, such as return nestedxxx. Then, when tester () is used, an error is returned.
In python, there is no tester () for methods ester and nested (). this is the use of nested (). Therefore, an error is returned if the ester and nested are class.

Hope to help you ~~

In python, can the _ init _ function be nested with other functions?

Of course. Check the closure"

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.