In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Today, I would like to share with you the relevant knowledge points about Python namespaces and scopes. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article.
Namespace what is a namespace
In Python, namespaces are places where object and name binding relationships are stored, so the question is, what is an object, what is a name, and what is a binding relationship?
1) at present, our understanding of objects can only stay on the basis of "everything is an object in Python". Functions are objects, classes are objects, variables, modules, and everything are objects. It is OK to have such cognition, and we will continue to supplement it when we have the opportunity.
2) names, very simple, each time we need to take names for the definition of modules, variables, functions and classes, and these names are put in the namespace
3) Python gives the binding relationship between the name and the data. For example, when we define a = 6, Python automatically binds the variable a to the object 6. We can use the de statement to unbind the binding relationship.
Now that you understand that namespaces are where objects and name bindings are stored, you can take a closer look at what categories namespaces can be divided into:
1) built-in namespaces-used to store various built-in functions (built-in functions) and built-in modules (built-in modules). For example, abs () is a built-in function, and the built-in namespace can be used anywhere in Python.
2) Global namespaces-names in global namespaces can be used anywhere in the same module
3) Local namespaces-names in local namespaces can only be used within functions.
The meaning of namespaces
The greatest function of namespaces is to prevent improper references caused by duplicate names. We can define a = 6 in the global namespace and a = 7 in the local namespace. There is no conflict between the two. This is the greatest role of namespaces to prevent improper references caused by repeated names.
Search order of namespaces
Knowing the meaning of namespaces, some readers will surely realize that I define a = 6 globally and a = 7 locally, so when I call the name a, which space will Python start looking for the object corresponding to a?
All I can say is, this reader, you are very good, and we will answer this question with examples.
A = 6 # define an ab in the global namespace = 8 # define a b in the global namespace to test whether you can find the global bdef test (): a = 7 # define a return a return (test ()) bprint (a) in the local namespace when calling a function.
(7pc8)
six
From our quiz above, the output a will be 7 when calling the function test, and 6 when using print (a) directly.
So we can boldly draw a conclusion:
1) when a function is called, the order in which the function looks for the name will be local namespace-> global namespace-> built-in namespace.
2) when the function is not called and the name is used directly, the search order is the global namespace-> built-in namespace.
3) as long as the corresponding name is found in a namespace (local or global), stop looking for it
4) it is feasible to define the same name in different namespaces, and subsequent definitions will not overwrite the original.
Detailed explanation of local namespace
There is a very amazing thing in local namespaces, because functions can be nested within each other, and it is normal to nest one function within another:
Def test_1 (): # define a function def test_2 (): # define a nested function print in test_1 ('praise the ball's kind-hearted people') # this is the simplest function nesting, # but also the most irregular function nesting, # because if it is not improved, the nested test_2 function cannot be used
The above is the simplest form of function nesting, so the problem arises one after another. as mentioned above, the local hit space is generated in the function, so if I define a nested function in a function, does that mean I created a local namespace in the local namespace?
That's right!
But in terms of terms, we would call test_2 the innermost namespace, and test_1 is what we call the satellite function namespace.
We can do this over and over again:
Def test_1 (): # define a function def test_2 (): # define a nested function def test_3 () in test_1: # define a nested function in the embedded function test_2 # omit 10,000 layers. The search order in the nested functions of print ("praise the kind-hearted people of the ball") print ("praise the kind-hearted people of the ball")
In the previous article, we have introduced the subsidiary function namespace and internal namespace generated by nested functions, so if you define the same name in both the satellite function namespace and the internal namespace, what is the search order?
B = 10 # define a bdef test_1 (): # define a function def test_2 (): # define a nested function a = 6 in test_1 # define an a return an in the internal namespace B a = 7 # define an a b = 8 # in the satellite namespace define a bprint (test_1 ()) # call function in the satellite namespace
If it is really written as above, then no result will be output, because we only call test_1, but test_2 is not used as a nested internal function. If you want to use a nested function, you can only return it by using the nested function as the return value.
So change the code.
B = 10 # define a bdef test_1 (): # define a function def test_2 (): # define a nested function a = 6 in test_1 # define an a return an in the internal namespace B a = 7 # define an a b = 8 # in the satellite namespace define a b return test_2print (test_1 () ()) # call function in the satellite namespace
ten
(6pr 8)
According to the modification, the result we get will be 6, and when we call the nested function, the nested function will start to look for that name in its own local space.
Just like calling the nested function test_2, it starts looking in its own local namespace and stops looking after finding a = 6
So we can come to a conclusion again:
1) when a nested function is called, its search order is internal namespace-> subsidiary function namespace-> global namespace-> built-in namespace.
2) when you find the corresponding name, you will stop looking.
About the use of nested functions b = 10 def test_1 (): def test_2 (): a = 6 return a return test_2print b a = 7 b = 8 return test_2print (test_1 () ()) # take a closer look at the process of calling the function
Why do you need to write two parentheses test_1 () () when calling a function instead of directly test_1 ()?
Let's take a closer look at the return value of the test_1 function. The return value of test_1 is a function object test_2, so if we just write a parenthesis to call the function, we will get a function object, that is, test_2.
Let's give an example.
B = 10 def test_1 (): def test_2 (): a = 6 return return test_2print b a = 7 b = 8 return test_2print (test_1 (), type (test_1 () # print out the result
The above is the result of the printout, which represents the function object
Maybe some readers want to sing a different tune, but what if I just want to write a test_1 () so that I can get the desired results directly?
I can only say that you have the potential to become a genius, because laziness is the cornerstone of human progress, this need can be realized, but we have to change the code like this:
B = 10 def test_1 (): def test_2 (): a = 6 return print b a = 7 b = 8 return test_2 () print (test_1 ()) # call the function
(6pr 8)
We did get the results we wanted. Think carefully about why.
Or because of the return value, the return value of the function test_1 is test_2 (), that is to say, the return result is the result of the function test_2 running, and the Russian doll has started again. The return value I get is the return value of another function!?
All I can say is, yes, it is.
But one thing to note when using this method is that embedded functions must be parameterless!
B = 10 def test_1 (): def test_2 (c): # randomly define a parameter a = 6 return a print b a = 7 b = 8 return test_2 () print (test_1 ()) # call the function
TypeError: test_1..test_2 () missing 1 required positional argument:'c'
This will report an error that the function test_2 () is missing a positional parameter named'c'.
So if you want to use this method, you need to pay attention to it.
But to put it another way, if the embedded function requires parameters, can't I define the parameters when I return?
This method is indeed feasible.
But if this is the case, it would be better to use the default parameter directly and define the parameter c directly when defining it.
The above is about the Russian doll namespace explanation, and then we will introduce the scope, if you can put the knowledge points in the namespace Li Jie, then the scope is no more than er er.
Scope what is scope
The scope is based on the namespace, which means the scope of the name
In fact, we have more or less covered the scope in the above.
The scope of the global variable b = 10 # is the full scope of the module def test_1 (): def test_2 (): a = 6 return a # b # because of the role of the global variable so the full scope To return b a = 7 b = 8 return test_2print (test_1 () ())
More or less, readers already know something about this scope.
I will directly put the conclusion as follows:
Built-in namespace-its scope is all modules in Python and can be used in all modules
Global namespace-its scope is all the scope of the module and can be used at will within the module
Local namespace-its scope is only within the function and can only be used within the function.
It may be because the scope is different, so the search order will be different, the larger the scope, the lower the priority of the search.
As mentioned above, even if there is the name an in both global and local, the function will be called from the local first.
Global statement
Different namespaces can define the same name so that there is no conflict, but this also means that we cannot modify the name binding relationship in the global when we are in the local namespace, so Python provides a way to solve this problem:
A = 10 # define a global statement def test (): global a # uses the global statement Declare the name an in the global namespace an a = 5 return aprint (a) # first print out what a was before the function was called print (test ()) # output the result print (a) # in the function to see if the an in the global has changed
ten
five
five
So we can know that after using the global statement, the names we use will be global namespaces.
Nonlocal statement
Since the name binding relationship in the global namespace can be modified locally, can the binding relationship in the satellite function namespace be modified in the internal namespace?
The answer is obviously yes, but you need to use the nonlocal statement.
Def test_1 (): def test_2 (): # define a nested function test_2 a = 15 def test_3 () in test_1: # nonlocal a # of Russian nesting dolls uses nonlocal to declare that the next an is the an of the affiliated namespace So is it in test_2 or in test_1? A = 5 print ('call test_3 to change the binding relationship of the name a') test_3 () print (f 'outputs a: {a}') a = 10 test_2 () print (f 'outputs the a value of the outermost function: {a}') test_1 ()
Call test_3 to change the binding relationship of the name a
Output aV5 in the satellite function namespace
Output a value of the outermost function: 10
From this we can know that the a used in calling the nonlocal declaration is in the function test_2, not in test_1
So the conclusion we can draw is:
1) in the process of using the nonlocal statement, the corresponding name will only be found up and modified once.
Topic
It's the same old rule. Write a question to test the above.
Def discount (price,rate): final_price = price * rate old_price = 6 print ('value of old_price', old_price) return final_priceold_price = float (input ('please enter price') rate = float (input ('please enter discount rate') print (discount (old_price,rate)) print ('value of old_price', old_price)
In the above code, suppose the old_price I entered is 100 and the rate is 0.6.
So, two questions.
What is the output value in print (discount (old_price,rate))?
What is the output value of print ('value of old_price', old_price)?
Summary
A namespace is a mapping table of names (variables) and objects.
Scope refers to the scope, or jurisdiction, of a namespace.
Variable search follows the LEGB principle, first from the grass-roots level (innermost function to find), and then to the municipal party committee (outer function). And then to the provincial party committee (module namespace) and finally to the central (builtin namespace).
Each namespace is independent of each other, and the creation time and life cycle are different.
Global is used to create and modify global variables within a function.
Nonlocal is used to modify the local variables of the outer function in the inner function.
Without declaring global and nonlocal, trying to modify the global variable or the local variable of the outer function will actually only create a new local variable in the function or inner function, and the global variable or the local variable of the outer function with the same name will not be affected.
All you can see here is a man!
These are all the contents of the article "how to use Python namespaces and scopes". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.