Understanding Python functions is the first class of objects

Source: Internet
Author: User

Turn from: https://foofish.net/function-is-first-class-object.html. Respect for the original, hereby declare!

——————————————————————————————————————————————————————————————————

A proper understanding of Python functions can help us to better understand the high-order techniques of Python decorators, anonymous functions (lambda), functional programming, and so on.

Functions are an integral part of the programming language, which is commonplace. But a function as the first class object (first-class object) is a major feature of the Python function. So what exactly is the first class of objects (First-class object)?

function is an object

All things are objects in Python, functions are no exception, functions can be assigned to a variable as an object, can be added to a collection object as an element, can be passed as a parameter value to other functions, and can be used as the return value of a function, which is unique to the first class of objects.

Let's look at a simple example

def foo (text): ...      return len (text) ... >>> foo ("Zen of Python")13

This is a simple function to calculate the length of the parameter text, which is called the function name followed by a parenthesis, followed by a parameter, the return value is an integer.

The function is an object that has three common properties of the object model: ID, type, and value.

>>> ID (foo)4361313816>>> type (foo)<class'  function'>>>> foo<function foo at 0x103f45e18>

As an object, a function can assign a value to a variable

>>> bar = foo

When you assign a value to another variable, the function is not called, just a new name is bound to the function object.

>>> Bar ("Zen of Python")13>>>

In the same way, you can assign the function to more variables, and the only change is that the reference count of the function object is constantly increasing, in essence these variables ultimately point to the same function object.

>>> a = foo>>> b = foo>>> c = bar is ctrue 

Functions can be stored in the container

A container object (list, Dict, set, and so on) can hold any object, including integers, strings, or functions that can be stored in a container object, such as

 >>> funcs = [foo, str, Len]  >>>  funcs[ <function foo at 0x103f45e18>, < Class   " str  ", <built-in  function Len>]  >>> for  F in   Funcs: ...  print  (F ( " hello   "  5hello  5>>> 

Foo is our custom function, and STR and Len are two built-in functions. When the for loop iterates through each element of the list, the function object assigns a value to the F variable, and the call F ("Hello") is the same as invoking the essence of foo ("Hello"), each time F points back to a new function object. Of course, you can also use the index of the list to navigate to the element to invoke the function.

>>> Funcs[0] ("Zen of Python ")#  equivalent to foo ("Zen of Python")8

function can be used as a parameter

A function can also be passed as a parameter value to another function, for example:

def Show (func): ...      = Func ("Zen of Python "#     ... Print ("length of string is:%s" % size) ... >>> is: 9

function can be a return value

function as the return value of another function, for example:

def Nick ():      ... return foo>>> Nick<function Nick at 0x106b549d8>>>> a = Nick ()>> > a<function foo at 0x10692ae18>>>> A ("python")6

can also be shortened to

>>> Nick () ("python")6

when a function accepts one or more functions as input or a function output (return) value is a function, we call such a function a higher-order function , such as show and Nick above are higher-order functions.

In Python's built-in functions, a typical high-order function is a map function , which takes a function and an iterative object as an argument, and then invokes it as a parameter, sequentially calling the element of the iteration object.

>>> map (foo, [" the","Zen"," of","python"])>>> lens = Map (foo, [" the","Zen"," of","python"])>>>list (lens) [3, 3, 2, 6]

The map function acts as:

 for inch ["the","Zen","of","  python"]][3, 3, 2, 6"

Only the map is running more efficiently.

Functions can be nested

Python also allows functions to be defined in a function called nested functions.

def get_length (text):      ... def Clean (t):           #  2         ... return t[1:]      ... = Clean (text)  #  1     ... return Len (new_text) ... >>> get_length ("python")5>>>

The purpose of this function is to remove the first character of the string and then calculate its length, although the function itself is not very meaningful, but it is sufficient to describe the nested function. get_length Call, the first execution of 1 code, found that there is a call to the clean function, then execute the code in 2, the return value is assigned to New_text , and then continue to execute the subsequent code.

>>> Clean ("python") Traceback ("recent")  :" <stdin> "  in <module>'clean' are not defined

Functions that are nested inside functions cannot be accessed outside the function, but are only used inside the function, and are not valid beyond the scope of the external function.

A class that implements __CALL__ can also be used as a function

For a custom class, if the __call__ method is implemented, then the behavior of the instance object of the class is a function, which is an object that can be called (callable). For example:

class ADD:     def __init__ (self, N):          = N    def__call__(self, x):        return SELF.N + x >>> add = Add (1)>>> Add (4)>>> 5

Executing add (4) is equivalent to calling add._call__ (Add, 4), and self is the instance object ADD,SELF.N equals 1, so the return value is 1+4

Add (4)  | | Add (1) (4)  | | Add. __call__ (Add, 4)

Determining whether an object is a callable object can be judged using the built-in function callable .

>>> callable (foo) True>>> callable (1) False>>> callable (int) True 

Summarize

Python contains functions such as everything is an object, the function as the first class object, support assignment to the variable, as a parameter to other functions, as the return value of other functions, supporting the nesting of functions, the implementation of the __call__ method of the class instance object can also be called as a function.

Understanding Python functions is the first class of objects

Related Article

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.