Python high-order functions

Source: Internet
Author: User

What is a higher order function? Follow the example step by step

Variables can point to functions

Using Python's built-in absolute value function abs, for example, there are several ways to call

>>> ABS (-10) 10

But what if I just write abs?

>>> abs<built-in function abs>

ABS (-10) is a function call, ABS is the function itself

We know that the result can be assigned to a variable, is the function possible?

>>> x=abs ( -10) >>> x10
y=abs>>> y<built-in function abs>

Conclusion: A function can also be assigned to a variable, that is, a variable can point to a function

Use this variable to call the function and give it a try.

>>> y (-10) 10

It worked!!! ABS (-10) and Y (-10) a hair

The function name is also a variable

The ABS () function can be thought of as ABS, which points to a function that can find an absolute value.

>>> ABS = 10>>> ABS ( -10) Traceback (most recent):  File "<stdin>", line 1, in <modu Le>typeerror: ' int ' object is not callable

ABS this variable points to 10, and then call ABS (-10) will be error, indicating that ABS is really a variable, if you want to use ABS normal function, can only restart the Python interactive environment.

What is a high-order function?

Since a variable can point to a function and a function can receive a variable, is it possible to pass the function as a variable into another function?

>>> def add (x, Y, F): Return F (x) + f (Y) >>> Add ( -2, 3, ABS) 5

  

Passing functions as arguments, such functions are called higher-order functions.

Python high-order functions

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.