Why use a function
- Maximize code reuse and minimize code redundancy
- Decomposition of processes
Writing functions
>>def statements
Creating a function in Python is done with the DEF keyword, and 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
(arg1,arg2,... ArgN):
Typically, there is a return statement in the body of the function that can appear anywhere in the body of the function, which represents the end of the function call and returns the result to the function call. But the return statement is optional and is not required. Technically, a function with no return value automatically returns the None object, but this value can be ignored.
>>def statements are executed in real time
A Python def statement 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 statements in Python are run in real time, without a process like independent compilation time) because it is a statement that can appear wherever any statement is present-even nested in other statements.
if test: def func (): ... else: def func (): ... func ()
It simply assigns a variable name at run time. Unlike a compiled language like the C language, Python functions do not need to be fully defined until the program is run, rather, the DEF is evaluated at run time, and the code in DEF is evaluated when the function is called.
Just like the other statements in Python, a function is simply an object, which is recorded in memory when the program executes. In fact, in addition to the call, the function allows arbitrary attributes to be attached to the record information for subsequent use:
Othername=func #Assign function Objectothername () #Call func againfunc () #call Objectfunc.attr=value #attach attribute
An example: defining and invoking
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 code above work correctly because "*" is valid for both numbers and sequences, and in Python we never have a similar declaration of variables, parameters, or return values, and we can use the times as multiplication of numbers or repetition of sequences.
In other words, the function of the Times is determined by the arguments passed to it, which is one of the core concepts of Python.
It is important to emphasize that if we pass in a parameter that does not support the function operation, Python will automatically detect the mismatch and throw an exception, thus reducing the need for us to write unnecessary type detection code.
>> Local Variables
All variables defined inside the function are local variables by default, and all local variables appear when the function is called and disappear when the function exits.
function Design Concepts
- Coupling: Use parameters for input and output use return statement.
- Coupling: Use global variables only when it is really necessary.
- Coupling: Do not change the parameters of a mutable type unless the caller wishes to do so.
- Aggregation: Each function should have a single, unified goal.
- Size: Each function should be relatively small.
- Coupling: Avoid changing variables directly in another module file.
- Function objects: Properties and annotations
>> Indirect function calls
Since Python functions are objects, we can write generic procedures for handling them. function objects can be assigned to other names, passed to other functions, embedded in data structures, returned from a function to another function, and so on, as if they were simple numbers or strings.
Assign the 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
Fill the function object into the data structure:
Schedule=[(Echo, ' spam! '), (Echo, ' ham! ')] for (Func,arg) in schedule: func (ARG)
As you can see from the code above, Python is very flexible!
>> function Introspection
Since the function is an object, we can use the regular object tool to handle the function.
Func.__name__dir (func)
The introspection tool allows us to explore the implementation details, such as the function has already attached the code object, the code object provides the function's local variables and parameters and other aspects of the details:
Dir (func.__code__) func.__code__.co_varnamesfunc.__code__.co_argument
Tool writers can use this information to manage functions.
>> Function Properties
The function object is not limited to the system-defined properties listed in the previous section, we can also attach arbitrary user-defined properties to the function:
func.count=0func.count+=1func.handles= ' button-press '
Such attributes can be used to attach state information directly to a function object without having to use other techniques such as global, non-local, and class. Unlike non-native, such attribute information can be accessed anywhere in the function itself. The name of this variable is local to a function, but its value remains after the function exits. A property is related to an object, not to a scope, but the direct effect is similar.
function annotations in the >>python3.0
In Python3.0 you can also attach annotation information to a function object-any user-defined data related to the parameters of the function. Python provides a special syntax for declaring annotations, but it does nothing on its own; annotations are completely optional and, when present, are simply attached to the __annotations__ property of the function object for use by other users.
Syntactically, function annotations are written on the DEF header line, and for parameters, they appear after the colon immediately following the parameter name, and for the return value, they are written immediately after the argument list.
def func (A: ' Spam ', B: (1,10), c:float), int: return a+b+c
Annotations and annotated functions are identical in function and use, except that the annotated function, Python collects the data of their annotations into a dictionary and attaches them to the function object itself. The parameter name becomes the key, and if you write a return value annotation, it is stored under key return, and the value of the annotation is assigned to the result of the annotation expression:
func.__annotations__ #Prints: {' A ': ' Spam ', ' C ':
, ' B ':(1,10), ' return ':
}
Watch out.
If you write 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 it is annotated with the string ' spam '.
The use of spaces between parts of the function head is optional.
Annotations are valid only in DEF statements.
Anonymous functions: Lambda
In addition to the DEF statement, Python provides a form of expression that generates a Function object. Because it is very similar to a tool in the Lisp language, it is called a lambda. Just like Def, this expression creates a function that can then be called, but it returns a function instead of assigning the function to a variable name. This is why lambda is sometimes called an anonymous function. In fact, they are often used in the form of an inline function definition, or as a deferred execution of some code.
>>LAMBDA-expression
The general form of a lambda is the 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 object returned by the lambda expression works exactly the same as the function object created and assigned by Def, but Lambda has a few differences that make it useful to play a particular role.
A lambda is an expression, not a statement.
The body of a lambda is a single expression, not a block of code.
The two pieces of code generate 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 as the code inside the def.
>> Why to use lambda
In general, lambda acts as a function sketch, allowing the definition of a function to be embedded within the code used. They are always optional, because they can always be replaced with def.
Lambda is typically 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 a dictionary or other data structure in Python to build more kinds of behavior tables:
Key= ' got ' {' already ':(lambda:2+2), ' Got ':(lambda:2*4), ' one ':(lambda:2 * 6]}[key] () #Prints: 8
Writing the code so that the dictionary becomes a more versatile branching tool.
Finally, it's important to note that Lambda can also be nested
((Lambda x: (lambda y:x+y)) (99)) (4) #Prints: 103
mapping functions in a sequence: map
The map function applies the passed-in function to each element in a sequence object, and returns a list containing the results of all function calls.
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 happens to be one of the most common places that lambda appears.
List (map (lambda x:x+10, counters)) #[11,12,13,14]
Functional Programming Tools: filter and reduce
In Python's built-in functions, the map function is the simplest built-in function representation of such tools for functional programming. The so-called functional programming is the tool that applies some functions to the sequence. For example, filter out some elements (filter), and apply a function to each pair of elements and run to the final result (reduce).
List (filter (lambda x:x>0), Range ( -5,5)) #[1,2,3,4]
The elements in the sequence will be added to the results list if their return value is true.
Reduce accepts an iterator to handle it, but it itself is not an iterator, it 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 above two reduce calls calculate the sum and cumulative product of all the elements in a list.