Python start a comprehensive analysis of variables in scope from the local and global variables

Whether it is class-based object-oriented programming, or simply variables inside a function definition, the scope of a variable is always a learning Python must understand and grasp the link, let's start from the local and global variables comprehensive analysis of the variables in Python scope, need friends can refer to the
understanding of global and local variables
variable names inside a function definition 1. If this is the first time, and before the = sign, then it can be considered to be defined as a local variable. In this case, regardless of whether the global variables used in the variable names are local variables used in the function. E.g:

num = 100
def func():
  num = 123
  print num
func()

The output is 123. Description variable names defined in the function num is a local variable, global variable covering. For another example:

num = 100
def func():
  num += 100
  print num
func()

The output is: UnboundLocalError: local variable 'num' referenced before assignment. Tip error: num local variables are applied before the assignment. That this variable is not defined to be misused. Thus proving once again here is the definition of a local variable, rather than global variables.

2. The function of the variable name if it is inside the first time, and appears after the = sign, and have been previously defined as a global variable, global variable references herein. E.g:

num = 100
def func():
  x = num + 100
  print x
func()

The output is 200. If before the variable name num is not defined as a global variable, an error message appears: variable is not defined. E.g:

def func():
  x = num + 100
  print x
func()

The output is: NameError: global name 'num' is not defined.

3. When used in the function of a variable, the variable name if both have local variables and global variables, use local variables default. E.g:

num = 100
def func():
  num = 200
  x = num + 100
  prinx x
func()

The output is 300.

4. In the definition of a variable in the function requires a global variable, global keyword. E.g:

num = 100
def func():
  global num
  num = 200
  print num
func()
print num

The output 200 and 200, respectively. This shows the function of the variable name as a global variable num is defined, and is assigned the value 200. For another example:

num = 100
def func():
  global num
  num = 200
  num += 100
  print num
func()
print num

The output 300 and 300, respectively.

Above in collating the results of global variables and local variables of the scenarios, I try to do some of the analysis (the Chinese part of the comment) on the first half of the teaching of the code of input fields:

# calculator with all buttons
 
import simplegui
 
# intialize globals
store = 0
operand = 0

Here called simplegui module, you can correct the http://www.codeskulptor.org/ operation. However, the module can not be used directly in python environment, you need to install SimpleGUICS2Pygame package.

# event handlers for calculator with a store and operand
 
def output():
"""prints contents of store and operand"""
  print "Store = ", store
  print "Operand = ", operand
  print ""

Output function defined in () are used as a store of global variables and operand. Refer to point 2.

def swap():
""" swap contents of store and operand"""
  global store, operand
  store, operand = operand, store
  output()

In the function swap (as defined) in the first operand of the store and made to define global variables. Without doing so, there is no error assignment was used then there will be. A first reference point may be. It is also not can be understood: The function swap (), in the case where no keyword global, Store the default operand and local variable, and the right part is used = false in the absence of assignment. Refer to point 3.

def add():
""" add operand to store"""
 
  global store
  store = store + operand
  output()

Here I encountered a problem since the first two weeks of course: that is why the add () function defines only store a global variable, but not the same way to define the operand. Now combined with the first point of view, because the store did not advance as a local variable assignment, it can not be used directly, while the operand is a global variable defined before it can be called directly to use.

Variable Scope
Variable Scope (scope) where in Python is an easy out of the pit.
Python's scope in a total of four, namely:

L (Local) local scope
E (Enclosing) outer closure function in the function
G (Global) global scope
B (Built-in) built scope
to L -> E -> G - > B of Find rules, namely: can not find at the local, local will go outside to find a local (eg closures), and then can not find the will to go global to find, in addition to the built-in look.

Python addition def / class / lambda, others such as: if / elif / else / try / except for / while not change its scope. Definition of variables within them, and still have access to the outside.

>>> if True:
...   a = 'I am A'
... 
>>> a
'I am A'

If the variable is defined in the language in which a, external or accessible.
Note, however, if if is def / class / lambda wrapped inside assignment becomes a local scope function / class / of the lambda.
Carried out within def / class / lambda assignment, becomes its local scope, local scope overrides the global scope, but will not affect the global scope.

g = 1 #全局的
def fun():
  g = 2 #局部的
  return g
 
print fun()
# 结果为2
print g
# 结果为1

But be careful, sometimes want to reference a global variable inside a function, ignoring the error occurs, such as:

#file1.py
var = 1
def fun():
  print var
  var = 200
print fun()
 
#file2.py
var = 1
def fun():
  var = var + 1
  return var
print fun()

Both functions being given UnboundLocalError: local variable 'var' referenced before assignment
before the assignment is not referenced error! why? Because inside, the interpreter function detects var be reassigned, and so became a local variable var, var but wanted to use until they are assigned, this error will appear. The solution is to add globals var inside a function but a function of running a global var will be modified.

Closures Closure
definition of closure: If an internal function, the variables in the outer function (but not in the global scope) is referenced, then the internal function is considered to be closure (closure)

Nested functions / closure scope:

a = 1
def external():
  global a
  a = 200
  print a
 
  b = 100
  def internal():
    # nonlocal b
    print b
    b = 200
    return b
 
  internal()
  print b
 
print external()

As will be error - referenced before assignment, Python3 have keywords nonlocal can solve this problem, but do not try to modify or Python2 the closure of variables. About a pit closures there:

from functools import wraps
 
def wrapper(log):
  def external(F):
    @wraps(F)
    def internal(**kw):
      if False:
        log = 'modified'
      print log
    return internal
  return external
 
@wrapper('first')
def abc():
  pass
 
print abc()

There will be referenced before assignment of error, because the interpreter is detected in the re-assignment if False, it will not go the closure of the external function (Enclosing) to find the variables, but if Flase does not hold is not executed, so there will be this error. Unless you need else: log = 'var' or if True, but this statement is no logic to add meaning, so try not to modify the closure of variables.

Like using conventional methods can not achieve closure so that the function of the counter, as carried out in an internal reference count + = assignment errors before 1 will appear to solve the nonlocal keyword or under way :( Py3 environment)

def counter(start):
    count =[start]
    def internal():
      count[0] += 1
      return count[0]
    return internal
 
count = counter(0)
for n in range(10):
  print count()
# 1,2,3,4,5,6,7,8,9,10
 
count = counter(0)
print count()
# 1

Since the list has variability, and the string is immutable.

locals () and globals ()
globals ()
, Ltd. Free Join and globals () is different, global keyword is used to declare a local variable as a global variable. globals () and locals () provides a way to access based on global and local variables dictionary

For example: If the function to define a local variable within 1, 2 another function of the same name, but have to reference the 2 function in a function.

def var():
  pass
 
def f2():
  var = 'Just a String'
  f1 = globals()['var']
  print var
  return type(f1)
 
print f2()
# Just a String
# <type 'function'>

locals ()
If you've used Python Web framework, then you must have had the need to pass a lot of local variables within a function to view template engine, and then act on HTML. While you can have some more intelligent approach, you also want a transfer is still a lot of variables. First do not understand the syntax is how come, what to do, we only need a general understanding of locals () is.
You can see, locals () gave the local variables pack and threw it together.

@app.route('/')
def view():
  user = User.query.all()
  article = Article.query.all()
  ip = request.environ.get('HTTP_X_REAL_IP',     request.remote_addr)
  s = 'Just a String'
  return render_template('index.html', user=user,
      article = article, ip=ip, s=s)
  #或者 return render_template('index.html', **locals())

We recommend the python learning sites, click to enter , to see how old the program is to learn! From basic python script, reptiles, django, data mining, programming techniques, work experience, as well as senior careful study of small python partners to combat finishing zero-based information projects! The method has timed programmer Python explain everyday technology, to share some of the learning and the need to pay attention to small details

Published 16 original articles · won praise 10 · views 10000 +

Guess you like

Origin blog.csdn.net/haoxun07/article/details/104486427