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 use python function nesting

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly introduces "how to use python function nesting". In daily operation, I believe many people have doubts about how to use python function nesting. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use python function nesting". Next, please follow the editor to study!

First, uncover the true face of the function name

We create a function to name actually represents a memory address, add parentheses to run the function body in the function, if you do not add parentheses, you can try it yourself, the output is a memory address, so it seems that he is actually similar to a variable, except that the function represents a function, so the function can also be passed into the function as an argument or returned as a return value.

Second, function nesting (functions in functions)

Def zhangsan ():

Def lisi ():

Print ("I am lisi")

Print ("I am zhangsan")

Lisi ()

Zhangsan ()

When we do not call lisi in the zhangsan function, I am lisi will not output. It is output only when it is called. The above is only level 2 nesting, and you can nest multiple times like a list.

Note: the keyword global cannot be used when we need to modify external variables internally in nested functions.

Global affects global variables outside the function. Need to use nonlocal (in python3), for example:

Age = 111,

Def zhangsan ():

Age = 18

Def lisi ():

Nonlocal age

Age + = 1

Print ("age of lisi", age)

Print ("age of zhangsan", age)

Lisi ()

Zhangsan ()

Print ("age:", age)

If we run it, we will find that age does not affect the age of the function (outside of zhangsan). If you change it to global, it will affect the global variable.

III. Closures

For example, a simple closure:

Def zhangsan ():

Age = 18

Def lisi ():

Print (age)

Return lisi

The concept of closure: first, it is a nested function, and secondly, it refers to the variables of the external function in the internal function, which we call a closure.

Secondly, why do we return lisi in the form of a return value? we can think about it, if we only want to use the function lisi, if we use the method in No. 2, every time we call zhangsan, then we have to go through zhangsan every time, which is obviously not what we want, so if we just want to call lisi, we can write: wangwu = zhangsan () # at this time wangwu represents the memory address of lisi, but does not execute it. Wangwu () # thus calls the internal function lisi and can refer to the variable age in zhangsan.

IV. Decorator

4.1 General decorator

First of all, think about a problem, we go to a web page, and then click on personal information, will remind us to log in to view, then we need to log in a lot of pages, each call is very troublesome, so there is a decorator.

It needs to follow one principle: the principle of opening and closing.

Open: it means to facilitate the expansion of new features, such as updates.

Closure: when extending new features, the original code cannot be modified.

For example:

Def login ():

Print ("login")

Def func ():

Print ("Click personal Information")

A writes the login, B writes the personal information, and if C wants to call the personal information, he doesn't want to call the login. B needs to combine the two functions, but he can't modify the original function, so he has:

Def login (func):

Print ("login")

Def log ():

Func ()

Return log

Def func ():

Print ("Click personal Information")

Func = login (func)

F ()

This problem can be solved with the knowledge of closures, and the method of func is called decorator. But as soon as we want to add func = login (func) so that we don't call the original function name, we have:

Def login (func):

Print ("login")

Def log ():

Func ()

Return log

@ login

Def func ():

Print ("Click personal Information")

Func ()

Instead of func = login (func), add an @ addition function name to the top of the function. We call it grammatical sugar. Well, it's so sweet.

Now calling func is equivalent to calling login, but when the func function has a return value, we can't get it according to the above writing, so modify it to:

Def login (func):

Print ("login")

Def log ():

Ret = func ()

Return ret

Return log

@ login

Def func ():

Print ("Click personal Information")

Return "ok"

Print (func ())

Summary: when we execute func (), we skip to @ login,@login, which is equivalent to executing func = login (func), and the login function is executed. The result of execution is returned to func, where the value obtained by func is the memory address of ok, and then back to func (), ok is output.

Here's the problem:

When our newly added function, that is, the func function needs an argument, how to add it in the decorator function? The next function may also require this decorator to require two parameters what to do? That is, if our parameters are dynamic, then add the dynamic parameters and modify the login function to:

Def login (func):

Print ("login")

Def log (* args,**kwargs):

Ret = func (* args,**kwargs)

Return ret

Return log

No matter how many are added at this time, it will not be affected.

4.2 decorator with parameters

First of all, if we add a parameter @ login (True), when we have a parameter, we take a look at @ and login (True). Login (True) gets the return value, the memory address of the log function is @ log. Obviously, where do we put our func? Obviously there will be an error, so we can nest another layer on the outside to:

Def log_out (F):

Def login (func):

Print ("login")

Def log (* args,**kwargs):

If F==True:

Ret = func (* args,**kwargs)

Return ret

Else:

Return "NO"

Return log

Return login

@ log_out (True)

Def func ():

Print ("Click personal Information")

Return "ok"

Print (func ())

In this way, according to the previous understanding, log_out (True) means login, which means @ login

We just add a switch to the original, that is, when the decorator has parameters, we need three layers of nesting.

4.3 one function uses multiple decorators

Def zhangsan1 (fun1):

Def lisi1 (* args,**kwargs):

Print ("111111 before executing the decorated function")

Fun1 (* args,**kwargs)

Print ("111111 after execution of decorated function")

Return lisi1

Def zhangsan2 (fun2):

Def lisi2 (* args,**kwargs):

Print ("222222 before executing the decorated function")

Fun2 (* args,**kwargs)

Print ("222222 after execution of decorated function")

Return lisi2

@ zhangsan1

@ zhangsan2 # zhangsan3 = zhangsan2 (zhangsan3)

Def zhangsan3 ():

Print ("I am the decorated function 333333")

Zhangsan3 ()

Result of execution:

111111 before executing the decorated function

222222 before executing the decorated function

I am the decorated function 333333

222222 after execution of the decorated function

111111 after execution of the decorated function

Execution order: first, when zhangsan3 is called, @ zhangsan2,@zhangsan2 is equivalent to zhangsan3 = zhangsan2 (zhangsan3), that is, lisi2 is returned, and then @ zhangsan1,@zhangsan1 is equivalent to zhangsan3 = zhangsan1 (lisi2). Note that the incoming function becomes lisi2, not zhangsan3, and lisi1 is returned, followed by a parenthesis execution, that is, the first sentence in lisi1. # execute the first 111111 of the decorated function, and then fun1 (), that is, lisi2 (), will output # the first 222222 of executing the decorated function. After returning to zhangsan2, the argument brought in becomes zhangsan3 again, so I output # I am the decorated function 333333, then output the decorated function 222222, and then go back to the place where it was originally called. Output # after the decorated function 111111.

At this point, the study of "how to use python function nesting" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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

Internet Technology

Wechat

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

12
Report