程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python namespace and scope

編輯:Python

Namespace (namespace)

1)、 name (name) With the object (object)

object : Object a storage area , Used to store values , It also contains a series of methods supported for this value , It also contains a series of properties .

name : Each name corresponds to an object , Multiple names can correspond to an object . This is a bit like aliases in other languages .

2)、 Namespace

Namespace : A namespace is a place for storing the correspondence between names and objects , stay python Namespaces in are generally used dict Data structure implementation .

stay python in , function 、 Modules have their own namespaces :

Local namespace (local namespace): That is, the name defined in the function —— Include variables in the function 、 Parameters 、 Local variables, etc ; With function , Die with function .

Global namespace (global namespace): The name defined in the module —— Include variables in the module 、 function 、 class 、 Parameters 、 Constant 、 Import (import) Modules, etc ; Born with modules , Die with the module .

Built in namespace (built-in namespace): namely python Built in names —— Including various built-in functions 、Exception etc. ; Born with the interpreter , Die with the interpreter .

ps: actually ,class It will also form a special namespace.

and , When python When you need to use variables , We will look for... In the above namespace in turn , The order is :

Local namespace , Global namespace 、 Built in namespace .

Cannot have duplicate names in the same namespace , But different namespaces can .

  • Can pass locals()( Get local namespace)、globals()( Get the big picture namespace) Function to get the value of the namespace ( Dictionaries ), The results may not be consistent at different locations of the program , Because the result is for the current position .

ps: because python It's done line by line , When there is a new name with object Conduct bind When , You will associate the name with object The corresponding relation of is added to the corresponding namespace.

Scope (scope)

Scope : It can be understood as the range of variables , Out of range, a variable cannot be used . stay python In the program , Direct access to a variable , All scopes will be accessed from the inside out until , Otherwise, the report will be wrong .Python There are only modules in (module), class (class) And function (def、lambda) To create a new scope , Other code blocks ( Such as if/elif/else/、try/except、for/while etc. ) No new scope will be generated .

Scopes can be divided into four types :

Local: The innermost layer , Contains local variables , It generally refers to the scope inside the function ;

Enclosing: Contains nonlocal but not global variables , Mainly when nested , Variables of the outer function , So relative to the inner function , Variables in nested outer functions are neither local variables nor global variables .

Global: Global variables , For example, global variables in the current module .

Build-in: Built-in variables .

The search order is generally :Local--->Enclosing--->Global--->Build-in

When a corresponding variable is found , Stop continuing with the outer scope search .

The search location is in the corresponding scope namespace( With code execution ,namespace Constantly changing , Add a name or delete a name .).

Scope map :

  • adopt nonlocal You can declare a variable as an outer scope variable , That is, in an inner scope, a name Associated with an outer scope , Then the interpreter knows to go to the outer scope to find the name The corresponding one object 了 .
  • adopt global You can declare a variable as a global scope variable , That is to say, to put a... Anywhere name Associated with global scope , Then the interpreter knows to go to the global scope to find the name The corresponding one object 了 .

# A typical example :

def scope_test():
def do_local():
spam = "local spam" #local scope
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam" #outer scope, What changed at this time scope_test As defined in spam Value .
def do_global():
global spam
spam = "global spam" #global scope, What changes at this time is global scope As defined in spam Value .
spam = "test spam"
do_local() # What has changed is local scope Medium spam.
print("After local assignment:", spam) #scope_test Medium spam.
do_nonlocal() # What has changed is scope_test Medium spam.
print("After nonlocal assignment:", spam) #scope_test Medium spam.
do_global() # What has changed is global scope Medium spam.
print("After global assignment:", spam) #scope_test Medium spam.
scope_test()
print("In global scope:", spam) # Output global scope Medium spam.

Running results :

After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

# Examples of variable search :

x=3
def g():
print(x) # local scope No statement x, So reference to global scope Of x.

Running results :3

x=3
def g():
x=2 # Define and assign local variables x
print(x) # Reference local variables x

Running results :2

x=1
def g():
print(x)
x=2
g()

Running results : error .

python The interpreter runs python The code is read and run line by line , But for functions , All are read once , So in the code above ,g() It is read in at one time , And the interpreter remembers g() Defined x=2, therefore x Will be referenced to local scope The variables in the x, however x It is not declared before use ( You must declare before using ), So wrong. .


# Two examples of functions

The function does not execute during the declaration definition phase , So you can use undefined names , But before running , These names must be well defined , Otherwise it will go wrong .

x=1
def f():
x=3
g()
print("f:",x) # 3
def g():
print("g:",x) # 1
f()
print("main:",x) # 1

There will be no mistakes here , Because before it runs , We have defined g().

x=1
def f():
x=3
g()
print("f:",x)
f() # Report errors
def g():
print("g:",x) 

There is a mistake here , This is because f() It's already running , however g() Not yet defined , So there was a mistake .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved