Functions of Python

Source: Internet
Author: User
Tags closure iterable

The meaning of the function

Functions are well-organized, reusable pieces of code that are used to implement a single, or associated function.

Functions can improve the modularity of the application, and the reuse of the code. You already know that Python provides a number of built-in functions, such as print (). But you can also create your own functions, which are called user-defined functions.

Definition of a function
    • The function code block begins with a def keyword followed by the function identifier name and parentheses ().
    • Any incoming parameters and arguments must be placed in the middle of the parentheses. Parentheses can be used to define parameters.
    • The first line of the function statement can optionally use the document string-for storing the function description.
    • The function contents begin with a colon and are indented.
    • return [expression] ends the function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.

Such as

def fun (formal parameter):    "Content"    return truefun (argument)
function parameters

When defining a function, it is declared that the formal parameter is simply a formal argument, and when the function is called, the parameter passed is the actual parameter abbreviation argument. And the formal parameter can be divided into four kinds

    • Required Parameters
    • Keyword parameters
    • Default parameters
    • Indefinite length parameter
Required Parameters

The required parameters must be passed into the function in the correct order. The number of calls must be the same as when declared

Def f1 (a):    print ("OK") F1 () def F2 (A, b)    print (a+b) F2 (3+4)

Return results: OK and 7

Note: When calling a prerequisite, the argument must correspond to the position of the parameter, otherwise an error will be encountered.

Keyword parameters

Keyword arguments are closely related to function calls, and function calls use keyword parameters to determine the values of the parameters passed in.

Using the keyword argument allows a function call when the order of the arguments is inconsistent with the Declaration, because the Python interpreter can match the parameter values with the name of the argument.

def info (name,age): Print ("    name%s"%name)    print ("Age%s"%age)  info ("flash", +) info ("AA", 19)

Output results

Name Flashage 18Name aaage 19
Default parameters

When a function is called, the value of the default parameter is considered to be the default value if it is not passed in.

def info (name,age,sex= "male"): Print ("    name%s"%name) print ("Age    %s"%age)    print ("Sex%s"%sex) info (" Flash "," info ("AA", 19,sex= "female")

Comparison of output results

Name flashage 18Sex malename aaage 19Sex Female
Indefinite length parameter

You may need a function that can handle more arguments than was originally declared. These parameters are called indefinite length parameters (also called dynamic parameters), and the above 2 parameters are different, the declaration is not named. One is the unnamed name parameter and the other is the named parameter.

No named parameter (tuple of output) def add (*args):    sum = 0    for i in args:        sum + = i    print (sum) Add (1,2,3,4,5) has a named parameter (output is a dictionary) def Fun (**kwargs):    for I in Kwargs:        print ("%s:%s"% (I,kwargs[i])) Fun (name= "flash", age=22)
Function call

Defines a function that gives the function a name, specifies the parameters contained in the function, and the code block structure.

Once the basic structure of this function is complete, you can execute it from another function call or directly from the Python prompt.

The simplest example

def fun ():    print ("OK") fun ()
function return value

Return statement [expression] exits the function, optionally returning an expression to the caller. A return statement without a parameter value returns none.

    • The function can stop execution and return the result as soon as it encounters a return statement, so can also be understood as a return statement that represents the end of the function.
    • If return is not specified in the function, the return value of this function is None
    • Return multiple objects, the interpreter assembles the multiple objects into a tuple as a result of a whole output
function scope

All variables of a program are not accessible in any location. Access permissions depend on where the variable is assigned. The scope of the variable determines which part of the program you can access which particular variable name.

Can be broadly divided into four situations

    • l:local, local scope, which is the variable defined in the function;
    • E:enclosing, the local scope of the nested parent function, which is the local scope of the ancestor function that contains the function, but not the global;
    • G:globa, a global variable, is a variable defined at the module level;
    • B:built-in, the variables inside the system fixed module, such as int, ByteArray, etc. The order of precedence for search variables is: scope local > Outer scope > Global >python in current module
Total = 0; # This is a global variable # writable function description def sum (arg1, arg2):   #返回2个参数的和. "   Total = Arg1 + arg2; # Total is a local variable here.   Print "function is a local variable:", total   
function recursion

Characteristics

    • Call self function
    • There is an end condition

The advantage of recursive functions is that they are simple in definition and clear in logic. In theory, all recursive functions can be written in a circular way, but the logic of the loop is not as clear as recursion.

The use of recursive functions requires careful prevention of stack overflow. In the computer, the function call is implemented through a stack (stack) of this data structure, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack of frames. Because the stack size is not infinite, there are too many recursive calls, which can cause the stack to overflow

For a simple example, ask for factorial of 5.

def f (i):    if i = = 1:        return 1    return I * f (i-1) print (f (5))

Summary

    • The advantage of using a recursive function is that the logic is simple and clear, and the disadvantage is that too-deep calls cause a stack overflow.
    • The language that is optimized for tail recursion can prevent stack overflow by tail recursion. The tail recursion is actually equivalent to the loop, and the programming language without the loop statement can only be looped by the tail recursion.
    • The Python standard interpreter is not optimized for tail recursion, and there is a stack overflow problem with any recursive function.
Higher order functions

Higher-order functions are called Higher-order function in English.

A variable can point to a function, which can receive a variable, and a function can receive another function as a parameter, a function called a higher order function.

    • Function names can be assigned
    • The function name can be used as a function parameter and can also be used as the return value of a function

As an example

def f (n):    return n *ndef F1 (a,b,f):    set = f (a) + f (b)    return Setprint (F1 (1,2,f))
The return value is 5
Closure function

What is a closure function, see a simple example

def foo ():    x = 5    def func ():        print (x)    return Funcfoo () ()
#返回值是5

We would think that x = 5 is a local variable that belongs to the Foo function, why can it be called? This is the closure feature of closures.

Definition: If a reference is made to a variable in an external scope (but not at the global scope) in an intrinsic function, then the intrinsic function is considered a closure (closure).

So for the above example, Func () is the closure function.

Generator

With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, the vast majority of the space behind it is wasted.

So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, which saves a lot of space. In Python, this side loop computes the mechanism, called the generator: Generator.

There are a number of ways to create a generator. The first method is simple, as long as a list of the generated formula is [] changed () to create a generator:

L = [x * x for x in range] #listg = (x * x for x in range) #生成器

The generator holds the algorithm, and if only the element is called, the best way is to use a for loop, because the generator is also an iterative object.

g = (x * x for x in range) for N in G:     

If the algorithm used to be very complex, we can use function call to implement. Like the Fibonacci sequence.

def fib (max):    N, a, b = 0, 0, 1 while    n < max-1:        #print (b)
Yield b A, B = B, a + b n = n + 1 return fib (6)
#这就是定义generator的另一种方法. If a function definition contains a yield keyword, then the function is no longer a normal function, but a generator:
Iterators

We already know that for there are several types of data that can be directly acting on a loop:

    • A class is a collection of data types, such as,,, list tuple dict set ,, and str so on.
    • One is generator to include the generator and yield the generator function with the band.

These objects, which can be directly applied to for the loop, are called iterative objects: Iterable .

How to determine if an object is an object that can be iterated, and can be judged using built-in functions

>>>from Collections Import Iterable>>> isinstance ([], iterable) true# if return True, no return False

Note:

    • Any object that can be used for for the loop is a Iterable type;
    • All objects that can be used for next() functions are Iterator types, which represent a sequence of lazy computations;
    • Collection data types such as list , dict ,, and str so on are Iterable not Iterator , however, you can iter() get an object from a function Iterator .

Here we may ask, is already an iterative, why is not iterator? This is because the Python Iterator object represents a data stream, and the iterator object can be next() called by the function and will return the next data continuously until there is no data to throw an StopIteration error. You can think of this data stream as an ordered sequence, but we can't know the length of the sequence in advance, only by continuously using the next() function to calculate the next data on demand, so Iterator the calculation is lazy, and it will only be calculated when the next data needs to be returned.

IteratorIt can even represent an infinitely large stream of data, such as the whole natural number. Using list is never possible to store all natural numbers.

Decorative Device

What is an adorner?

An adorner is essentially a function that handles other functions that allow additional functions to be added without the need to modify the code, and the return value of the adorner is also a function object. The essence is to encapsulate the original function inside another function, so that it is equal to a new function in the execution of the contents of the new function.

Let's start with a simple example, in many of the functions we've written beforehand, if we want to add a new feature, it's not possible to write to each function again, which is an unwise thing to do. Here we'll use the decorator. For example

def f1 (FD):    def f ():        print ("OK")        fd ()        print ("OK")        # return R    return f@f1def F2 ():    print ( "F2") F2 ()

This is one of the simplest adorners. Where the @ symbol is the syntax for the adorner in Python.

Of course, the adorner can also specify parameters to more easily perform such as

Import Timedef Logger (flag = "True"):    def show_time (f):        def func ():            start = Time.time ()            f ()            end = Time.time ()            if flag = = "True": Print                ("Print log")            print (End-start)        return func    return Show_ Time@logger ("true") def foo1 ():    print ("OK!!!!!!!!!!!!!")    Time.sleep (1) foo1 () def foo2 ():    print ("OK!!!!!!!!!!!!!")    Time.sleep (2) Foo2 ()

can also pass the indefinite length parameter to do the simple computation

Import Timedef Show_time (f):    def func (*args,**kwargs):        start = Time.time ()        f (*args,**kwargs)        End = Time.time ()        print (End-start)    return func@show_timedef foo1 (*args,**kwargs):    Sum = 0 for    i in Args:        sum + = i    print (sum)    time.sleep (1) foo1 (all in all)

Summary:

In the object-oriented (OOP) design pattern, the decorator is called the adornment mode. The Deco pattern of OOP needs to be implemented through inheritance and composition, while Python supports decorator directly from the syntax level, in addition to the decorator of OOP. Python's decorator can be implemented using functions or classes.

 

Functions of Python

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.