Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to parse the basic knowledge of Python function

2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about the basic knowledge of how to parse Python functions, which may not be well understood by many people. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.

I. the basis of function

Simply put, a function is a combination 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, so 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'm sure a lot of people have this experience at the beginning). We can extract the same code into a function that only needs to be called where needed. So, this increases the reuse rate of the code, and the overall code looks more concise and less bloated.

Function is a very basic program structure in Python, which is used to fully reuse our code; at the same time, function can divide a complex system into manageable parts, simplifying programming and code reuse.

Next, let's take a look at what a function is and how to define it. There are two ways to define a function, which are the def and lambda keywords.

1. Function definition

Let's sum up why we use functions.

Code multiplexing minimizes and minimizes redundant code; process decomposition (disassembly). Break down a complex task into multiple small tasks.

The syntax of a function definition is:

Def func_name (arg1, arg2, arg3,..., argN): statement return value

According to the above definition, it can be described simply as: a function in Python is a block of statements with 0 or more parameters, several lines of statements, and a return value (optional) (note indentation).

So let's define a relatively simple function that has no arguments and enters the ipython interactive environment:

In [1]: def hello ():...: print ('Leave me alone, the world')...:

Call (execute) the function:

In [2]: hello () Leave me alone, the world

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

As we said, there are two forms of defining a function, and the other is to use lambda to define it. The functions defined by lambda are anonymous functions, which we will explain later, which will not be shown here.

Second, function parameters

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

Python's function definition is very simple, but it is very flexible. In addition to the normally defined required parameters, default parameters, variable parameters, and keyword parameters can also be used to make the interface defined by the function not only deal with complex parameters, but also simplify the code of the caller.

1. Default parameter

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

Def inc (init, step=1): return init + step # call this function > inc (3) 4 > inc (3,2) 5

The default parameter has a pit, that is, the non-default parameter should be placed in front of the default parameter (otherwise the Python interpreter will report a syntax error). Multiple default parameters are allowed, but the default parameters need to be placed on the * side of the parameter list.

Def append (x, lst= []): return lst.append (x)

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 the exact name of lst.)

The modified function is:

Def append (x, lst=None): if lst is None: lst= [] lst.append (x) return lst

Generally speaking, when the default parameter is variable, we need to pay special attention to the scope problem, we need the above skills (immutable data type is value passing, variable data type is reference passing.) . Currently, the mutable object is list,dict,set,bytearray.

The default parameters are useful, but they can fall into the hole if they are not used properly. The default parameter has a large pit, which is demonstrated as follows:

# define a function, pass in a list, add an END, and then return

Def add_end (L = []): L.append ('END') return L

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

> > add_end ([1, 2, 3]) [1, 2, 3, 'END'] > add_end ([' x,'y,'z']) ['x,'y,'z, 'END']

When we call with the default parameter, the initial result is also correct:

> add_end () ['END']

However, when add_end () is called again, the result is incorrect:

> add_end () ['END',' END'] > add_end () ['END',' END', 'END']

The reasons are 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 content of the default parameter will change the next time it is called, and it is no longer the [] of the function definition.

So, one thing to keep in mind when defining default parameters: default parameters must point to immutable objects!

To modify the above example, we can use the immutable object None:

Def add_end (L=None): if L is None: l = [] L.append ('END') return L

Why design immutable objects like str and None? Because once an immutable object is created, the data inside the object cannot be modified, thus reducing errors caused by modifying the data. In addition, because the object is unchanged, there is no need to lock the object to read at the same time in the multitasking environment, and there is no problem at all. When we write a program, if we can design an immutable object, we should try to design it as an immutable object.

two。 Position parameter

Let's first write a function to calculate x ^ 2:

Def power (x): return x * x

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 parameter x:

> power (5) 25 > power (15) 225

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? It is impossible for us to define multiple functions. We can change power (x) to power (x, n), which is used to calculate x ^ n.

Def power (x, n): s = 1 while n > 0: n = n-1 s = s * x return s

3. Keyword parameter

Variable parameters allow us to pass in 0 or any parameters, which are automatically assembled into a tuple when the function is called. Keyword parameters allow you to pass in 0 or any parameters with parameter names, which are automatically assembled into a dict inside the function. Examples are as follows:

Def person (name, age, * * kwargs): print ('name:', name,' age:', age, 'other:', kwargs)

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

> person ('LavenLiu', 25) name: LavenLiu age: 25 other: {}

You can also pass in any number of keyword parameters:

> person ('LavenLiu', 25) name: LavenLiu age: 25 other: {} > person (' Taoqi', 25, city='Hebei') name: Taoqi age: 25 other: {'city':' Hebei'} > person ('James', 31, gender='M', job='NBA player') name: James age: 31 other: {' gender': 'Hebei',' job': 'NBA player'}

What is the use of keyword arguments? It can extend the function of the function. For example, in the person function, we are guaranteed to receive the parameters name and age, but we can also receive them if the caller is willing to provide more parameters. Imagine that you are doing a user registration function, except for the user name and age is required, the other is optional, using keyword parameters to define this function can meet the registration requirements.

Similar to variable parameters, you can assemble a dict first, and then convert the dict into keyword arguments:

> kwargs = {'city':' Hebei', 'job':' Test'} > person ('Taoqi', 25, * * kwargs) name: Taoqi age: 25 other: {' city': 'Hebei',' job': 'Test'}

4. Position parameters and keyword parameters

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

This is useful when default parameters are combined with keyword parameters.

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

Def minus (x, y): return x-y minus (3,5) # position parameter, position pass parameter minus (5,3) # position parameter, position pass parameter minus (x, y) 3) # keyword parameter, keyword pass parameter minus (x, y) # keyword parameter, keyword pass parameter

Positional parameters and keyword parameters can coexist, but keyword parameters must be written after positional parameters.

5. Variable position parameter

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

Variable position parameter.

In [1]: def fn (* args):...: print (args)...: In [2]: fn ((1,2,3,4)) ((1,2,3,4),) In [3]: tup01 = (1,2,3,4) In [4]: fn (tup01) ((1,2,3,4),) In [5]: fn (* tup01) (1,2,3,4)

In the function of python, you can also define variable parameters. Variable parameters means that the number of parameters passed in is variable.

In [6]: def cacl (* numbers):...: sum = 0.: for n in numbers:: sum = sum + n * n.: return sum.: In [7]: nums = [1, 2, 3] In [8]: cacl (* nums) # is there a problem if you don't add * before nums? Out [8]: 14

6. Variable keyword parameter

Variable keyword parameters are defined using * *, and in the body of the function, variable keyword parameters are a dictionary. The key of variable keyword parameters is a string and conforms to the specification for defining identifiers.

Def fn (* * kwargs): print (kwargs) dict01 = {'name':' Laven Liu', 'age': 29} fn (* * dict01) # fn (dict01) fn (name='Laven Liu', age=29) {' name': 'Laven Liu',' age': 29} {'name':' Laven Liu', 'age': 29}

Variable position parameters can only be called in the form of position parameters. Variable keyword parameters can only be called in the form of keyword parameters.

In [18]: def fn (* args, * * kwargs):...: print (args)...: print (kwargs)...: In [19]: fn (1, 2, 3, aquifer 1, baked 2) (1, 2, 3) {'az: 1, 'baked: 2} In [20]: def fn (* args, x, y): print (args)...: print (x) Y): In [21]: fn (1,2,3,4)-TypeError Traceback (most recent call last) in ()-> 1 fn (1,2,3) 4) TypeError: fn () missing 2 required keyword-only arguments:'x 'and' y' In [22]: fn (1,2, xylene 3, yellow4) (1,2) 3 4

Variable parameter post variable parameter does not appear with default parameter

7. Parameter combination

Functions can be defined in Python with required parameters, default parameters, variable parameters, and keyword parameters, all of which can be used together, or only some of them, but note that the order of parameter definitions must be: required parameters, default parameters, variable parameters, and keyword parameters

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

> def func (a, b, cym0, * args, * * kwargs):. Print ('a =', a,'b =', b,'c =', c, 'args =', args, 'kwargs =', kwargs)

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

> > func (1,2) a = 1 b = 2 c = 0 args = () kwargs = {} > func (1, 2, cations 3) a = 1 b = 2 cations 3 args = () kwargs = {} > func (1, 2, 3, 'asides,' b') a = 1 b = 2 cations 3 args = ('a','b') kwargs = {} > func (1, 2, 3, 'asides,' bins, xylene 99) a = 1 b = 2 cations 3 args = ('a'') 'b') kwargs = {' xcow: 99} >

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

> args = (1,2,3,4) > > kwargs = {'xchocolate: 99} > func (* args, * * kwargs) a = 1b = 2c = 3 args = (4,) kwargs = {' xchocolate: 99}

So, for any function, you can call it in a form similar to func (* args, * * kwargs), no matter how its arguments are defined.

8. Parameter deconstruction

Parameter deconstruction occurs when a function call occurs and a variable parameter occurs when a function definition occurs. Parameter deconstruction can be divided into two forms, one is position parameter deconstruction, the other is keyword parameter deconstruction.

Two forms of parameter structure:

Deconstruct the position parameter, using an asterisk. The deconstructed object is an iterative object, and the result of deconstruction is the position parameter. Keyword parameter deconstruction, using two asterisks. The deconstructed object is the dictionary and the result of the deconstruction is the keyword parameter.

An example of location parameter deconstruction:

In [23]: def fn (a, b, c):...: print (a, b, c)...: In [24]: lst = [1, 2, 3] In [25]: fn (lst [0], lst [1] Lst [2]) 1 2 3 # can also call In [26]: fn (* lst) # this practice is called parameter deconstruction 123 # * the linear structure can be unpacked into position parameters lst = [1,2,3,4] fn (* lst) #-> fn (lst [0], lst [1], lst [2], lst [3] TypeError: fn () takes 3 positional arguments but 4 were given

# an error was reported here. Originally, this function can only accept three position parameters. Lst has four elements. After parameter deconstruction, it becomes four parameters, so it reports an error.

Let's take a look at an example of dictionary deconstruction:

In [27]: d = {'averse: 1,' baked: 2, 'centering: 3} In [28]: fn (* * d) 1 2 3 # * * can solve the dictionary into keyword parameters

Parameter deconstruction occurs during a function call. When deconstructing, the deconstruction of linear structure is the position parameter, and the dictionary deconstruction is the key parameter.

The order of passing parameters: position parameters, linear structure deconstruction; keyword parameters, dictionary deconstruction. Try to use both deconstructions as little as possible, unless you really know what you're doing.

In [29]: def fn (a, b, c, d):...: print (a, b, c, d)...: In [30]: fn (0, * [2], cations 1, * * {'dudes: 3}) 0 2 1 3

9. Parameter slot (keyword-only parameter)

Introduced in Python3.

Def fn (a, b, c): print (a, b, c) fn (a, b, c)

If you want to force the passed parameter to be a keyword parameter:

Def fn (*, a, b, c): print (a, b, c) > fn (1, 2, 3) Traceback (most recent call last): File ", line 1, in fn (1, 2, 3) TypeError: fn () takes 0 positional arguments but 3 were given > fn (aquifer 1, 2, 3) 1 2 3

The parameters after # * must be passed in the form of keyword parameters, which are called parameter slots.

Parameter slots are usually used in conjunction with default parameters.

> > def fn (a, b, *, x, y): print (a, b) print (x, y) > fn (1, 2, 3, 4) Traceback (most recent call last): File ", line 1, in fn (1, 2, 3, 4) TypeError: fn () takes 2 positional arguments but 4 were given > fn (1, 2, xylene 3, yellow4) 1 2 34 > > fn (1, 2, * {'xylene: 3,' yearly: 4}) 1 2 3 4 def fn (a, b) *): print (a, b) def fn (a, b, *): Print (a, b) File "", line 1 SyntaxError: named arguments must follow bare * A few examples: def fn01 (*, x * 1, y * 5): print (x) print (y) > > fn01 () 1 5 def fn02 (x x, *, y): print (x) print (y) > > fn02 (y) 1 3

The pit of the parameter slot:

* after that, there must be parameters, non-named parameters and default values, named parameters may not have default values. Default parameters should not be used when parameter slots are used in each section of parameters. Variable key parameters must be placed after named parameters.

III. Advanced usage

1. Recursive function

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

Def fact (n): if nameplate 1: return 1 return n*fact (nmur1)

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

The language optimized for tail recursion can prevent stack overflow through tail recursion. Tail recursion is in fact equivalent to a loop, and a programming language without loop statements can only implement a loop through tail recursion.

two。 Anonymous function lambda

Python uses lambda to create anonymous functions.

Lambda is just an expression, and the function body is much simpler than def.

The body of 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 its own parameter list or in the global namespace.

Although the lambda function looks like it can only write one line, it is not the same as C or C++ 's inline function, which is designed to increase efficiency by not consuming stack memory when calling small functions.

Fib = lambda nMagazine x Zhongry 1 if not n else fib (fib (20)

3. Polymorphism in Python function

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

Def times (xmemy): return xpeny > times (2pr 4) > 8 times ('Python',4) # passed a different data type' PythonPythonPythonPython'

IV. Summary

The function of Python has a very flexible parameter form, which can not only achieve simple calls, but also pass in very complex parameters.

The default parameter must be an immutable object, if it is a mutable object, there will be logic errors in running!

Note the syntax for defining variable and keyword parameters:

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

* * kwargs is a keyword parameter, and kwargs receives a dict.

And how to pass in the syntax of variable parameters and keyword parameters when calling a function:

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

Keyword parameters can either be passed directly to: func (axi1, bread2), or you can assemble dict first, and then pass in: func ({'axiom: 1,' baked: 2}) via kwargs.

Using * args and * * kwargs is the idiom of Python. Of course, you can also use other parameter names, but you should use idioms.

After reading the above, do you have any further understanding of the basics of how to parse Python functions? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report