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 understand the scope of Python variables

2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

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

A closure is a function that is nested within a function. The decorator is just a special scenario of the closure, especially if the parameter of the outer function points to a function address to be decorated (not necessarily the address ha, as long as it is random), then there is a "@ xxx", which is quite interesting. The function of the decorator is to fill in new functions for the original function without changing the code of the original function. In terms of writing, it is still relatively simple and elegant.

The popular way of writing decorators

# def out (func): def inner (* args, * * kwargs): print ("we are checking...", args [0]) return func (* args, * * kwargs) return inner@outdef check_2019_nCov (name): return f "now, {name} is very healthy..." tmp = check_2019_nCov ('youge') print (tmp) # outputwe are checking... Yougenow, youge is very healthy...

Pass parameters to the decorator

Although the writing of this "@" requires that the parameter of the outer function is a func address, in order to pass the parameter, you only need to package a layer of function (the function is to accept the parameter), which is equivalent to expanding the function space and getting the parameter.

# the outermost function is to pass parameters def get_param (* args, * * kwargs): def out (func): def inner (* args, * * kwargs): print ("get params", args, kwargs) return func (* args, * * kwargs) return inner return out@get_param ("youge") def check_2019_nCov (name): return f "now {name} is very healthy... "tmp = check_2019_nCov (" youge ") print (tmp) # outputget params ('youge',) {} now, youge is very healthy...

This kind of decorator transfer parameter application scenario, in the Web application, take Flask as an example, is all routing url concepts, such as route ("/ login"), the principle is to use a variety of decorators to achieve routing-> view mapping.

If you look closely, the whole process ignores an important topic, that is, namespaces, and the scope of variables, or what namespaces look like.

LEGB rule

Namespace

As explained in detail in the previous article, the essence of Python variables is pointers and references to objects, while everything in Python is an object. This object is the memory address where the data is actually stored and is an instance of various classes (data types, data structures). (variables are used to refer to objects) something like that.

The most intuitive explanation:

"A namespace is a mapping from names to objects". (mapping of variable names and objects)

"Most namespaces are currently implemented as Python dictionaries." (most namespaces are implemented through dictionaries)

That is, namespaces are constraints used to avoid variable naming conflicts. Namespaces are independent of each other. Names cannot be repeated in one space, and there is no relationship between different spaces. Just like a computer system, the logic of storing files is the same.

For i in range (10): print (I) # these two sentences both use I, but their respective spaces are different. [i for i in range (100)]

Built-in space: (built-in names): Python built-in name, such as built-in function, exception class. Global space: (global names): constant, the name defined in the module (class, import module)... Enclosed: functions that may be nested within functions, etc. Local name: (local names): the name defined in the function (the variable within the function).

The order of Python search variables is: Local-> Enclosed-> Global-> Built-in.

In fact, from my personal experience, I can distinguish the relativity between the part and the whole. That's it, basically. Intuitively, take a py file that writes code as an example. The outermost layer is variable, class definition, function definition, from from.. Import.. Variable or function name, these are global variables, outermost classes or functions, inside are their respective namespaces.

# var1 is globalvar1 = 666def foo (): # var2 is local var2 = 666def foo2 (): # embedded local var3 = 666 # print (var2) print (var3) # G-> L is not found. # search for var2 is L-> E is ok in foo2 # it is not possible to find var2 in foo.

In fact, it is very easy to understand. As far as the previous code is concerned, according to L-E-G-B 's rule, it is OK to understand a relative.

Global vs local

Total = 0 # global def sum (a, b): "override built-in sum"total = a + b print (" local total: ", total) sum (1,1) print (" global total: ", total) # output local total: 2 Global total: 0

As you can see, the local will not change the global, but in the local can get the global variable. Otherwise, how can the inner function get the parameters received by the outer function of the closure? It is the outer function, which expands the scope of the inner function and is searched according to L-> E-> G-> B rule.

Global and nonlocal

Name = "youge" def change_name (): name = "youyou" # want to change "youge" to "youyou" change_name () print (name) # outputyouge

It's natural to find that you can't change it. Because, when calling a function, the name inside is a Local variable, which will not affect the global name. If you want to change the global variable inside the function, you can declare the variable with the global keyword.

Name = "youge" def change_name (): global name name = "youyou" # want to change "youge" to "youyou" change_name () print (name) # outputyouyou

Quite simply, inside the function, you can declare it as a global variable with global. Similarly, for the nesting of * * functions, that is, closures, decorators, etc., variables within the function are declared as Enclose layers outside the function through the implementation of the keyword nonlocal * *

Name = "jack" def outer (): name = "youge" # function has a local function space def inner (): name = "youyou" print ("local:", name) inner () # try to change name print ("encolse:", name) print ("global:", name) outer () # outputglobal: jacklocal: youyouencolse: youge

Now you want to modify the name of layer E in the inner function (L layer), that is, declare name as nonlocal in inner.

Name = "jack" def outer (): name = "youge" # function has a local function space def inner (): nonlocal name name = "youyou" print ("local:", name) inner () # try to change name print ("encolse:", name) print ("global:", name) outer () # outputglobal: jacklocal: youyouencolse: youyou

In the function nesting scenario, the name of the enclosed layer is changed by declaring name as nonlocal in the local layer. But if you declare global at the local layer, it doesn't work. Why, um... It is not clear yet, it is also experimental, temporarily.

Oh, suddenly want to post, I am still a rookie, often make a small mistake:

Name = 'youge'def change_name (): name = name + "youyou" change_name () print (name) # outputUnboundLocalError: local variable' name' referenced before assignment

The reason is that there is no definition of name in the space inside the function. In Python, the storage of function procedures is realized by recursive stack. Making use of the FILO of the stack, when a function is encountered, the participating members will be put into the stack in turn, and if there is a return, it will be set as a stack element.

Variables should be defined first and then used. The definition in Python means that the variable points to an instance object rather than a type declaration in other languages.

Modify name to a global variable, which can be passed through function parameters:

# method 1: define a separate function to handle name = 'youge'def change_name (s): name = s + "youyou" print (name) # global variable to pass to the function space, that is, "define first, execute later") change_name (name) # outputyougeyouyou

# method 2: declare it global. Name = 'youge'def change_name (): global name name = name + "youyou" change_name () print (name) # outputyougeyouyou is not recommended

At this point, the study on "how to understand the scope of Python variables" 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

Development

Wechat

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

12
Report