Summarize the usage points of functions in Python programming, and the main points of python

Source: Internet
Author: User

Summarize the usage points of functions in Python programming, and the main points of python

Why use functions

  • Maximize code reuse and minimize code Redundancy
  • Process Decomposition

Compile Functions

> Def statement
Create a function in Python using the def keyword. The def statement creates a function object and assigns it to a variable name. The general format of the def statement is as follows:

def <name>(arg1,arg2,... argN):  <statements>

Generally, a return statement can appear anywhere in the function body. It indicates the end of the function call and returns the result to the function call. However, the return statement is optional and is not required. Technically, a function without return values automatically returns the none object, but this value can be ignored.

> Def statements are executed in real time.
The def Statement of Python is actually an executable statement: when it runs, it creates a new function object and assigns it to a variable name. (Keep in mind that all the statements in Python are run in real time and there is no such process as the independent Compilation Time.) because it is a statement, it can appear where any statement can appear-or even nested in other statements.

if test:  def func():    ...else:  def func():    ......func()

It simply assigns a value to a variable name during runtime. Unlike the C language, Python functions do not need to be fully defined before they are run. To be more precise, def is evaluated at runtime, the code in def is evaluated only when the function is called.

Like other statements in Python, a function is only an object and is cleared and recorded in the memory during program execution. In fact, in addition to calling, a function allows any attribute to be appended to record information for subsequent use:

othername=func #Assign function objectothername() #Call func againfunc() #call objectfunc.attr=value #attach attribute

Example: define and call

def times(x,y):  return x*ytimes(2,4) #return 8times(3.12,4) #return 12.56times('Ni',4) #return 'NiNiNi'

The three calls to the function in the above Code can be correctly run, because "*" is valid for numbers and sequences. in Python, we have never made similar declarations on variables, parameters, or return values, we can use times as the multiplication of numbers or the repetition of sequences.

In other words, function times depends on the parameters passed to it. This is one of the core concepts of Python.

It should be emphasized that if we input a parameter that does not support function operations, Python will automatically detect the mismatch and throw an exception, in this way, we can reduce unnecessary types of detection code.

> Local variables
All variables defined in the function are local variables by default. All local variables will appear when the function is called and disappear when the function exits.

Function Design Concepts

  • Coupling: Use parameters for input and return statements for output.
  • Coupling: Use global variables only when necessary.
  • Coupling: Do not change variable type parameters unless the caller wishes to do so.
  • Aggregation: each function should have a single and unified goal.
  • Size: each function should be relatively small.
  • Coupling: Avoid directly changing variables in another module File.
  • Function object: attributes and annotations

> Indirect function call
Since Python functions are objects, we can write common programs to process them. Function objects can be assigned to other names, passed to other functions, embedded into the data structure, and returned to another function from one function, just as they are simple numbers or strings.

Assign a function to another variable:

def echo(message): print(message)x = echox('Indirect call!')  #Prints:Indirect call!

Pass to other functions:

def indirect(func,arg):  func(arg)indirect(echo,'Argument call')  #Prints:Argument call

Enter the function object in the data structure:

schedule=[(echo,'Spam!'),(echo,'Ham!')]for (func,arg) in schedule:  func(arg)

From the code above, we can see that Python is very flexible!

> Function Introspection
Since functions are objects, we can use conventional object tools to process functions.

func.__name__dir(func)

The introspection tool allows us to explore implementation details. For example, the function has already attached code objects, and the code objects provide details about the local variables and parameters of the function:

dir(func.__code__)func.__code__.co_varnamesfunc.__code__.co_argument

Tool writers can use this information to manage functions.

> Function Attributes
Function objects are not limited to the System-defined attributes listed in the previous section. You can also attach any user-defined attributes to the function:

func.count=0func.count+=1func.handles='Button-Press'

Such attributes can be used to directly append state information to function objects without using other technologies such as global, non-local, and class. Different from non-local, such attribute information can be accessed anywhere in the function itself. The name of this variable is local for a function, but its value is retained after the function exits. Attributes are related to objects rather than scope, but the direct effect is similar.

> Function annotation in Python3.0
In Python3.0, you can also add annotation information to function objects-any user-defined data related to function parameters. Python provides special syntax for declarative annotations, but it does not do anything on its own. Annotations are completely optional and, when this occurs, the _ annotations _ attribute is directly appended to the function object for other users.

In terms of syntax, function annotations are written in the def header line. For parameters, they appear after the colon following the parameter name; for return values, they are written after a-> followed by the parameter list.

def func(a:'spam',b:(1,10),c:float) -> int:  return a+b+c

Annotations and functions that have not been annotated are exactly the same in terms of functions and usage. However, annotation functions, python collects the data of their annotations into the dictionary and attaches them to the function object itself. The parameter name is changed to a key. If the return value annotation is compiled, it is stored under the return key, and the annotation value is the result assigned to the annotation expression:

func.__annotations__ #Prints:{'a':'spam','c':<class 'float'>,'b':(1,10),'return':<class 'int'>}

Notes

If you have compiled an annotation, you can still use the default value for the parameter. For example, a: 'spam' = 4 means that the default value of parameter a is 4 and the string 'spam' is used to annotate it.
It is optional to use spaces between parts of the function header.
The annotation is only valid in the def statement.
Anonymous function: lambda

In addition to def statements, Python also provides an expression form for generating function objects. It is called lambda because it is similar to a tool in the LISP language. Like def, this expression creates a function that can be called later, but it returns a function instead of assigning the function to a variable name. That is why lambda is sometimes called an anonymous function. In fact, they are often used in the form defined by a function in the row, or used to delay the execution of some code.

> Lambda expressions
Lambda is generally in the form of a keyword lambda, followed by one or more parameters followed by a colon followed by an expression:

lambda argument1,argument2,...argumentN:expression using arguments

The function objects returned by lambda expressions work exactly the same as those created by def and assigned values, however, lambda has some differences that make it useful when playing a specific role.

Lambda is an expression rather than a statement.
The body of lambda is a single expression, not a code block.
The following two sections of code generate functions with the same function:

def func(x,y,z):return x+y+zfunc(2,3,4)          #Return 9f = lambda x,y,z : x + y + zf(2,3,4)           #Return 9

Default parameters can also be used in lambda

x=(lambda a="fee",b="fie",c="foe": a+b+c)x("wee")           #Prints:'weefiefoe'

The code in the lambda body follows the same scope lookup rule like the code in def.

> Why lambda?
Lambda usually plays a role in writing functions quickly, allowing you to embed a function definition in the code in use. They are always optional, because they can always be replaced by def.

Lambda is usually used to write jump tables:

L=[lambda x: x ** 2,  lambda x: x ** 3,  lambda x: x ** 4]for f in L: print(f(2))      #Prints:4,8,16print(L[0](3))      #Prints:9

In fact, we can use the dictionary or other data structures in Python to construct more types of behavior tables:

key='got'{'already':(lambda: 2+2), 'got':(lambda: 2*4), 'one':(lambda: 2 ** 6)}[key]()     #Prints:8

Writing code in this way can make the dictionary a more common multi-path branch tool.

Finally, lambda can also be nested.

((lambda x:(lambda y: x+y))(99))(4)   #Prints:103

Ing function in sequence: map

The map function applies the passed-in function to each element of a sequence object and returns a list containing all the function call results.

counters=[1,2,3,4]def inc(x):return x+10list(map(inc,counters))     #[11,12,13,14]

Because map expects to pass in a function, it is exactly one of the most common places where lambda appears.

list(map((lambda x: x+10),counters)) #[11,12,13,14]

Functional programming tools: filter and reduce

In Python built-in functions, map functions are the simplest built-in functions used for functional programming. The so-called functional programming is a tool for applying functions to sequences. For example, filter some elements and apply functions to each pair of elements and run them to the final result (reduce ).

list(filter((lambda x: x>0),range(-5,5)))  #[1,2,3,4]

If the returned value of an element in the sequence is true, it will be added to the result list.

Reduce accepts an iterator for processing. However, it is not an iterator and returns a single result.

from functools import reduce  #Import in 3.0,not in 2.6reduce((lambda x,y: x+y),[1,2,3,4]) #Return:10reduce((lambda x,y: x*y),[1,2,3,4]) #Return:24

The preceding two reduce calls calculate the sum and product of all elements in a list.

Articles you may be interested in:
  • Analysis on function decorators written in Python
  • Examples of function (closure) usage in Python Functions
  • The example explains how to call and define functions in Python.
  • In-depth introduction to the use of parameters in Python functions and the traps of default parameters
  • Use Python built-in modules and functions to convert numbers in different hexadecimal formats
  • Usage Analysis of element traversal using the enumerate function in python
  • Exploring the use of open functions in python
  • Python nested functions use external function variables (Python2 and Python3)
  • Use * args and ** kwargs in Python functions to pass variable length parameters
  • Analysis of Function Definition instances in python Development
  • In-depth analysis of function parameters and scopes in Python

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.