Python scopes and namespaces

Python Scopes and Namespaces

 

namespace is a mapping from names to objects. 

Namespace is a mapping from names to objects (points, a clear path).

Most namespaces are currently implemented as Python dictionaries。

Most of them are implemented by the dictionary dict (other languages ​​also known as hash).

example:

the set of built-in names. Placing a set of built-in functions. Global name module; local name of the function call. In a sense, properties of a collection of objects is also a form of naming space.

namespaces is that there is absolutely no relation between names in different namespaces.

There is no relation between names in different namespaces, that is the same name, in a different namespace is nothing to do.

 

Life cycle lifetimes.

Namespaces are created at different moments and have different lifetimes.

E.g:

Module global namespace is created when the module definition is read, and continue until the interpreter quits. Built-name actually exists in a module builtins in.

local namespace function is created when the function is called, it is deleted when the function returns or throws ❌ not processed within a function.

 

Scope

scope is a textual region of a Python program where a namespace is directly accessible.

A scope is a code region, a namespace can be directly referenced area.

I understand:

Formed inside calls the function namespace (mapping / pointer / path / the hash), may be used inside the function code defines the external function name corresponding to the name of the object to obtain. Then the function code outside the code area may be directly used is a function of the scope.

 

⚠️ outside the scope function is a function definition in a position, corresponding to the positions corresponding to the time instead of calling.

 

⚠️: Reference the article: https://www.linuxidc.com/Linux/2018-12/155918.htm

 

 

Namespace search order:

 The Local : searched first, innermost layer (Innermost) containing the name of the local scope, such as the function / method / class internal local scope;

 Enclosing : The nesting level search from inside to outside, comprises any non-local (nonlocal) non-global (nonglobal) enclosing scope function name. The two nested scope function, the inner function of a local scope, the scope is the outer function Enclosing the inner function of the scope;

 , Ltd. Free Join : penultimate been searched, include the name of the global scope of the current module;

 -In Built : last search, the outermost layer contains the name of the built-in scope.

Python accordance with the above LEGB of the order in four scopes search name, there is no search, Python NameError throw an exception.

Used an analogy to understand namespaces and scope: 

  four kinds of scopes equivalent of our national life (Built - in ), province (Global), city (Enclosing), county (Local), equivalent to the civil service roster namespace , a record which is what people post. National civil servants in the service of 
the people (the country people can call him work), provincial civil servants to serve only the people themselves (national level people or people from other provinces I do not care), city (Enclosing), county (Local) is a reason. When we are looking for a certain type of leadership (such as looking for 
when a policeman to help me fight) (To access a name), if I was inside, look for a priority in the county leadership roster in the county (Local) (in priority own namespace scopes in to find), the county police did not find a roster roster went to the city (to 
the level of scope namespace to find), know where to find the national level have not found, it will error. If people want to find a provincial police to help you, not to find the city or county, only to find their own provincial (other provinces will not work), or find a national. National, 
provincial, city and county must have been in there, you can not move (the scope is static); leadership can be a general term move to the substitutions (namespace is dynamic, every time a new namespace will function calls the function execution

 

 

The difference glocal and nonlocal

First, the two different functions.

After identifying the key global variable modified variable is a global variable, the variable is modified modify global variables, and the nonlocal keyword modified variable identifies the variable is a function of the local variables, if the parent does not function the presence of a local variable, nonlocal position error occurs.

def f1():
    # i = 1
    def f2():
        nonlocal i
        print(i)
        i = 2
    f2()
    print(i)

f1()
# SyntaxError: no binding for nonlocal 'i' found

 

 

Second, the use of two different ranges.

  • global keyword can be used anywhere, including uppermost layer functions and nested functions, even if it is not defined before, after global modification can also be used directly.
  • nonlocal keywords can only be used in nested function, and the outer layer function defined in the corresponding local variable, or an error will occur.
= I 0
 DEF F1 (): 
    I =. 1
     DEF F2 ():
         Global I      # rebind
         Print ( " Global " , I) 
        I = 2 
    F2 () 
    Print ( " local " , I) 

F1 () 
# Output: 
# , Ltd. Free Join 0 
# local 1

 

 

 

A few examples:

i = 1

def f1():
    print(i)

def f2():
    i = 2
    f1()

f2()

print(i)

#输出
#1
#1

 

Explanation: This example, outside the scope of the described functions, the external code when a function definition.

 

IF True: 

  i = 1 Print (i) # normal output value i 1, will not be given

 

Explanation: This shows if the statement does not produce a new scope, only function / class will produce a new scope.

 

for I in Range (10 ): 

  Pass 

Print (I) # output is 9, not NameError

 

Explanation: unrelated scope, i is declared, and assignment.

 

def test():

    print(i)

  i= 2

i = 0

test()

 

Explanation: reports an error, UnboundLocalError: local variable 'i' referenced before assignment. i have been occupied. It can no longer be re-statement.

 

class A(object):

    a = 2

    def fun(self):

        print(a)

new_class = A()

new_class.fun()
#NameError: name 'a' is not defined

 

Explanation: do not understand. fun function collar external action, there is no a.

 

Guess you like

Origin www.cnblogs.com/chentianwei/p/11969856.html