Based on Python function basis, parameters, and advanced usage analysis

First, the function basis

Simply put, a function is a combination of a set of Python statements that can be run one or more times in a program. Functions in Python are also called procedures or subroutines in other languages, and these wrapped statements are called by a function name.

With functions, we can greatly reduce the number of times we copy and paste code (I believe many people have this experience in the beginning). We can extract the same code into a function, and only need to call it where needed. So, this increases the reuse rate of the code, the overall code looks more concise, not so bloated.

Functions are the most basic program structure in Python to maximize the multiplexing of our code; at the same time, functions can divide an intricate system into manageable parts, simplifying programming and code reuse. .

Next we look at what a function is and how it should be defined. There are two ways to define functions, namely def and lambda keywords.

Function definition

First summarize why you want to use a function?

Maximize code reuse and minimize redundant code;

Process decomposition (disassembly). Disassemble a complex task into multiple small tasks.

The syntax of the function definition is:

According to the above definition, it can be simply described as: a function in Python is a block of statements (with indentation) that has zero or more arguments, has several rows of statements, and has a return value (the return value is optional).

Then we define a simpler function that takes no arguments and enters the ipython interactive environment:

Call (execute) the function:

We found that the hello() function does not have a return statement. In Python, if the return statement is not explicitly executed, the return value of the function defaults to None.

We said that there are two forms of defining functions, the other one is defined using lambda. The function defined by lambda is an anonymous function, which we will explain in the following content, here is not a table.

Second, the function parameters

When defining a function, we determine the name and location of the parameter, and the interface definition of the function is complete. For the caller of the function, you only need to know how to pass the correct parameters, and what kind of value the function will return. The complex logic inside the function is encapsulated and the caller does not need to understand.

Python's function definition is very simple, but the flexibility is very large. In addition to the normally defined mandatory parameters, you can also use the default parameters, variable parameters and keyword parameters, so that the interface defined by the function can not only handle complex parameters, but also simplify the caller's code.

Default parameter

The default parameters make the API simple but flexible. When a parameter has a default value, the default value is used if the parameter is not passed when called.

The default parameter has a pit, which is the non-default parameter to be placed in front of the default parameter (otherwise Python's interpreter will report a syntax error). Multiple default parameters are allowed, but the default parameters need to be placed at the end of the parameter list.

There is a problem with this function. (The formal parameter in the function is a global variable? lst is called lst in the append function, but in the global scope, we don't know what name lst is.)

The modified function is:

In general, when the default parameters are mutable, you need to pay special attention to the scope problem. We need the above techniques (the immutable data type is value passing, and the variable data type is reference passing.). Currently variable objects are list, dict, set, and bytearray.

The default parameters are useful, but they can be dropped if not used properly. The default parameter has the largest pit, as shown below:

When we call it normally, the result seems to be good,

When we call with the default parameters, the results are correct at the beginning.

However, when add_end() is called again, the result is wrong.

The reasons are explained as follows:

When the Python function is defined, the value of the default parameter L is calculated, that is, [], because the default parameter L is also a variable, which points to the object []. Each time the function is called, if the content of L is changed, The next time the call is made, the content of the default parameter changes, not the [] function when the function is defined.

Therefore, to define the default parameters to keep in mind: the default parameters must point to the invariant object!

To modify the above example, we can use the None object to achieve this.

Why design an invariant object such as str and None? Because once the invariant object is created, the data inside the object cannot be modified, which reduces errors caused by modifying the data. In addition, because the object does not change, the object is not locked at the same time in the multi-tasking environment, and there is no problem reading at the same time. When we write a program, if we can design an invariant object, try to design it as an invariant object.

2. Positional parameters

Let's first write a function that computes x^2:

For the power(x) function, the parameter x is a positional parameter. When we call the power function, we must pass in one and only one parameter x:

Now, what if we want to calculate x^3? You can define another power3 function, but what if you want to calculate x^4, x^5, x^n? We can't define an infinite number of functions. We can change power(x) to power(x, n) to calculate x^n.

3. Keyword parameters

Variable parameters allow us to pass zero or any number of arguments that are automatically assembled into a tuple when the function is called. The keyword argument allows you to pass in 0 or any arguments with parameter names that are automatically assembled into a dict inside the function. An example is as follows:

The function person accepts the keyword argument kwargs in addition to the required parameters name and age. When calling this function, you can pass only the required parameters:

You can also pass in any number of keyword arguments:

What is the use of keyword parameters? It can extend the functionality of a function. For example, in the person function, we guarantee that we can receive the two parameters name and age, but if the caller is willing to provide more parameters, we can also receive it. Imagine that you are doing a user registration function. Except that the username and age are required, all other options are available. Using the keyword arguments to define this function will satisfy the registration requirements.

Similar to a mutable argument, you can also assemble a dict first, and then pass the dict to a keyword argument:

4. Location parameters and keyword parameters

Positional parameters and keyword arguments are concepts when a function is called.

Useful when combined with default parameters and keyword arguments.

The keyword argument must be written after the positional argument, otherwise a syntax error will be thrown.

The position and keyword parameters can coexist, but the keyword parameters must be written after the positional parameter.

5. Variable position parameters

The variable position parameter is defined by *, and in the body of the function, the variable position parameter is a tuple.

Variable position parameters.

In Python's functions, you can also define variable parameters. Variable parameters are the number of parameters passed in are variable.

6. Variable keyword parameters

Variable keyword parameters are defined using **, and in the body of the function, the variable keyword parameter is a dictionary. The keys of the variable keyword parameters are all strings and conform to the identifier definition specification.

Variable position parameters can only be called in the form of positional parameters

Variable keyword parameters can only be called as keyword arguments

Variable position parameters must precede variable keyword parameters

Variable parameter post

Variable parameters do not appear with default parameters

7. Parameter combination

To define functions in Python, you can use mandatory parameters, default parameters, variable parameters, and keyword parameters. These four parameters can be used together, or only some of them, but please note that the order of parameter definition must be: Required parameters, default parameters, variable parameters, and keyword parameters

For example, define a function that contains the above four parameters:

When the function is called, the Python interpreter automatically passes the corresponding parameters according to the parameter position and parameter name.

The most amazing thing is that through a tuple and dict, we can also call this function:

So, for any function, it can be called in the form of func(*args, **kwargs), no matter how its arguments are defined.

8. Parameter deconstruction

Parameter destructuring occurs when a function is called, and when a variable parameter is defined by a function. Parameter deconstruction is divided into two forms, one is position parameter deconstruction and the other is keyword parameter deconstruction.

Two forms of parameter structure:

Decoupling positional parameters, using an asterisk. The deconstructed object is an iterable object, and the result of the destructuring is a positional parameter.

Keyword parameter destructuring, using two asterisks. The deconstructed object is a dictionary, and the deconstructed result is a keyword parameter.

An example of location parameter deconstruction:

Based on Python function basis, parameters, and advanced usage analysis

Next look at the example of dictionary deconstruction:

Parameter destructuring occurs when the function is called. When deconstructing, the destructuring of linear structures is a positional parameter, and dictionary deconstruction is a keyword parameter.

The order of the parameters: positional parameters, linear structure deconstruction; keyword parameters, dictionary deconstruction. Use two deconstructions as little as possible, unless you really know what to do.

9. Parameter slot (keyword-only parameter)

Introduced in Python 3.

If you want to force the passed parameters to be keyword arguments:

The parameter slot is usually used in conjunction with the default parameters.

A few examples:

Pit of the parameter slot:

* Must have parameters after

When a non-named parameter has a default value, the named parameter can have no default value.

The default parameters should be at the end of each parameter

Variable position parameters cannot be used when using parameter slots, and variable key parameters must be placed after named parameters

Third, advanced usage

Recursive function

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

recursive function

The advantage of using recursive functions is that the logic is simple and clear. The disadvantage is that too deep calls can cause stack overflows.

Languages ​​optimized for tail recursion can prevent stack overflow by tail recursion. The tail recursion is in fact equivalent to the loop, and programming languages ​​without loop statements can only implement loops through tail recursion.

2. Anonymous function lambda

Python uses lambdas to create anonymous functions.

A lambda is just an expression, and a function body is much simpler than a def.

The body of a lambda is an expression, not a block of code. Only limited logic can be encapsulated in lambda expressions.

The lambda function has its own namespace and cannot access parameters outside of its own parameter list or in the global namespace.

Although the lambda function seems to only write one line, it is not equivalent to the inline function of C or C++. The purpose of the latter is to call the small function without occupying the stack memory and increasing the running efficiency.

Example display

3. Polymorphism in Python functions

The meaning of an operation depends on the type of object being manipulated:

Fourth, summary

Python's functions have very flexible parameter shapes that allow for simple calls and very complex parameters.

The default parameters must use immutable objects. If it is a mutable object, there will be a logic error in the operation!

Pay attention to the syntax for defining variable parameters and keyword parameters:

*args is a variable parameter, args receives a tuple;

**kwargs are keyword arguments, and kwargs receive a dict.

And how to pass the variable arguments and keyword arguments when calling a function:

Variable parameters can be passed directly to: func(1, 2, 3), or list or tuple can be assembled first, then passed through *args: func(*(1, 2, 3));

The keyword argument can be passed directly to: func (a=1, b=2), or it can be assembled first and then passed through kwargs: func({'a': 1, 'b': 2}).

Using *args and **kwargs is a customary way of writing Python. Of course, other parameter names can be used, but it is best to use idioms.

Cloth board connection board type switch

Electric Motor Centrifugal-Switches,Electric Motor Centrifugal -Pump,Electric-Boat Motor Electric Car Motor,Single Phase Start Stop Switch

Ningbo Zhenhai Rongda Electrical Appliance Co., Ltd. , https://www.centrifugalswitch.com

This entry was posted in on