Python Notes - function

Previous:

Python not only very flexibly defined functions, and it built itself a lot of useful functions can be called directly.

Here is the record about the contents of their own learning, because it is a white, so a lot of basic things will record it, mainly to deepen your own impression.

Information from the Liao Xuefeng teacher's official website , as well as instructional videos beep station.

 

call function:

To call a function, you need to know the name and function parameters, you can view documents directly from the official website of Python: http://docs.python.org/3/library/functions.html#abs

 

The number of parameters passed when calling the function is not hate, will get an error, such as:

Data type conversion

Python built-in function further comprises a common data type conversion functions, such as int () function can be converted to other data types are integers:

The function name is actually a reference to a function object, you can put the function name assigned to a variable, which is equivalent to this function from an "Alias":

This variable is like a pointing abs, abs so it can call a function through a.

 

Defined functions:

In Python, a function to define the def statement sequentially write the function name, parentheses, brackets and colon parameters: and then, write the function block body in the retracted, the function returns the value returned by return statement.

For example, we customize a function of the absolute value of my_abs example:

 

You can also write

 

Save my_abs () function is defined as 1.py files, then it can be started in the current directory of the file Python interpreter , with from 1 import my_abs import my_abs () function, a note file name (excluding. py extension):

 

Empty function:

If you want a definition of doing nothing is an empty function, you can use the pass statement. In fact pass can be used as a placeholder, for example, now have not figured out how to write the code function, you can first put a pass, so that the code can be up and running.

pass can also be used in other statements, the lack of a pass, the code will run with grammatical errors, such as:

 

Check the parameters:

When you call the function, if not the number of parameters, Python interpreter will automatically check it out and throw TypeError:

However, if the parameter type is not correct, Python interpreter will not be able to help us check. Try different my_abs and the built-in functions abs:

When an incoming inappropriate parameters, built-in function abs will check the parameters of the error, and we my_abs defined no parameter check, if statements will lead to error, error messages and abs are not the same. So, this function definition is not perfect.

Let's change the definition of my_abs, do check on the parameter type, allowing only integer and floating point types of arguments. Data type checking can be built-in function the isinstance () implementation:

 

Return multiple values:

Coordinates are given, displacement and angular, can calculate new coordinate, introducing Import statement indicates math math package, and allows subsequent code referenced math bag sin, cos and the like functions.

Then, we can get a return value at the same time:

 

The return value is a tuple! However, in the grammar, it returns a tuple parentheses may be omitted, and a plurality of variables may simultaneously receive a tuple, corresponds to a value assigned by location, so that, Python's return multiple values ​​actually returns a tuple, but more convenient to write . This is just an illusion, Python function returns a single value remains:

 

 

Function parameters

Python function definition is very simple, but the flexibility is very large. In addition to the normal definition of mandatory parameters, default parameters may be used, the variable parameters and keyword parameters, the function interface definitions such that it not only can handle complex parameters, may also simplify the code of the caller.

Positional parameters

We are here to write a function X² calculated for power (x) function, x parameter is a positional parameter.

When we call the power function, it must have passed only one argument and x:

 

That used to calculate the n-th power of X how to do? So that we can put power (x) modified to power (x, n):

power (x, n) function takes two parameters: x and n, these two parameters are position parameters, the function is called, passing the two positions in accordance with the order values ​​assigned parameters x and n.

 

The default parameters

The new power (x, n) function definition is no problem, but the old calling code fails because we added a parameter, resulting in old code because of lack of a parameter can not be called normal:

This time, the default parameters on rafts handy. Python error message is clear: call the function power () the lack of a position parameter n. As calculated X² could write:

In this way, when we call power (5), equivalent to calling power (5, 2).

 

When you set the default parameters, there are several points to note :

One is a mandatory parameter first, followed by the default parameters, otherwise the Python interpreter will complain (think about why the default parameters can not be placed in front of mandatory parameters);

Second, when a function has a plurality of parameters, the parameters placed in front of a large change, a small change in the parameters put back. Small changes in parameters can be used as the default parameters.

 

The default function of the maximum benefit is to reduce the difficulty of calling functions,

For example, we now need to pass two parameters name and gender. In this way, calling enroll () function requires only two arguments:

 

When Python functions defined, the default value of the parameter L was calculated out, i.e., [], because the default parameter L is also a variable that points to the object [], every time the function is called, if L is changed content, the next call, the default parameters are changed, no longer a function definition [] a.

Note: The default parameter must point to the same objects!

 

None that we can use to achieve the same objects, such as:

Immutable objects Once created, the data inside an object can not be modified, thus reducing errors due to changes in data due.

 

variable parameter

Mathematical entitled example, given a set of numbers a, b, c ......, calculated a2 + b2 + c2 + .......

To define this function, we must determine the parameters entered. Since the number of parameter uncertainty, we first thought can put a, b, c ...... as a list or tuple passed in:

When the call first with a list or tuple :( correct errors for comparison)

 

We changed to a variable parameter function parameters:

We just added a parameter in front of an asterisk, meaning it does represent quite different. Received inside the function parameter is a tuple numbers, the function is called, any number of parameters can be passed, including 0 parameter.

 

Keyword arguments

Keyword arguments What is the use? It can extend the functionality of the function. For example, in the person function, we can ensure that the received name and age of these two parameters, however, if the caller is willing to provide additional parameters, we can receive. Imagine you're making a user registration function, in addition to user name and age are required, other options are available, use keyword parameters to define the function will be able to meet the registration requirements.

 

Keyword parameters allow you pass containing 0 or any number of parameter name parameter, these parameters are automatically assembled as keywords inside a dict function, then, to pass in the dict converts keywords parameters:

Simplified wording:

This represents the extra ** extra dict of all key-value keyword arguments passed to the function with the parameters ** kw, kw will get a dict, dict kw attention to a copy obtained is extra, and not changes to kw It will affect the extra external functions.

 

Named keyword arguments

For caller keyword parameters, function parameters can be passed to any keyword unrestricted. As to what passed in the end, we need to function within kw checks.

If you want to limit the name keyword arguments, you can use named key word parameters, for example, receive only the city and the job as keyword arguments. ** kw different keywords and parameters, named keyword arguments require a special separator *, * the latter argument is considered named keyword arguments. This function is defined in the following manner:

If the function has been defined in a variable parameter, followed later named keyword arguments no longer need a special separator * a:

Named keyword arguments must be passed in the parameter name, and location of these different parameters. If you do not pass the parameter name, the call will be given:

Due to the lack parameter names when calling the city and job, Python interpreter these four parameters are treated as positional parameters, but the person () function accepts only two positional parameters. Named keyword arguments can have default values, which simplifies the call, because the city named keyword argument has a default value, when you call, do not pass city parameters:

When using named keyword arguments, pay special attention to, if there is no variable parameters, it is necessary to add a * as a special separator. In the absence of *, Python interpreter will not recognize the location and named keyword arguments.

Parameter combination

Defined function in Python, can be a mandatory parameter, default parameter, the variable parameter, keywords and named keyword parameters, these five parameters can be used in combination. Note, however, the order of the parameters must be defined: mandatory parameters, default parameters, variable parameter, named keyword arguments and keyword arguments.

Note: Although you can a combination of up to five parameters, but do not use too many combinations, or poor intelligibility function interface.

Such as the definition of a function, including the several parameters, when the function call, Python interpreter position automatically according to the parameters and the corresponding parameter name parameter passed into:

By a tuple and dict, you can also call the above function:

 

recursive function:

Inside the function, you can call other functions. If a function calls itself within itself, this function is a recursive function.

! For example, we compute the factorial of n = 1 x 2 x 3 x ... xn, with the function fact (n) represents, it can be seen:

fact (n) = n! = 1 x 2 x 3 x ... x (n-1) xn = (n-1)! xn = fact (n-1) xn. Therefore, fact (n) may be represented as nx fact (n-1), n ​​= 1, only require special handling.

So, fact (n) is written in a recursive way:

Advantage is to define a simple recursive function, clear logic. In theory, all recursive functions can be written in a circular fashion, but not as good as recursive loop logic is clear.

 

Recursive function needs to be taken to avoid stack overflow. As the stack size is not unlimited, so the number of recursive calls too much will lead to a stack overflow:

 

Recursive call stack overflow is solved by tail-recursion optimization, tail recursion means that, when the function returns, calls itself itself, and, return statement can not contain expressions. In this way, the compiler or interpreter you can do to optimize tail recursion, the recursive call to itself, no matter how many times, only occupy a stack frame, stack overflow situation does not occur.

 

To change the tail-recursive manner, it requires a bit more code is mainly the product of each step should passed to a recursive function:

return fact_iter (num - 1, num * product) returns only the recursive function itself , NUM - 1 and num * product will be evaluated before the function call does not affect the function call.

Guess you like

Origin www.cnblogs.com/qi-yuan/p/12629755.html