相关疑难解决方法(0)

范围规则的简短描述?

Python范围规则究竟是什么?

如果我有一些代码:

code1
class Foo:
   code2
   def spam.....
      code3
      for code4..:
       code5
       x()
Run Code Online (Sandbox Code Playgroud)

在哪里x找到?一些可能的选择包括以下列表:

  1. 在封闭的源文件中
  2. 在类命名空间中
  3. 在函数定义中
  4. 在for循环索引变量中
  5. 在for循环中

在执行期间,当函数spam在其他地方传递时,也存在上下文.也许lambda函数的传递方式有点不同?

某处必须有简单的参考或算法.对于中级Python程序员来说,这是一个令人困惑的世界.

python scope dynamic-languages

451
推荐指数
8
解决办法
24万
查看次数

在python中赋值错误之前引用

在Python中我收到以下错误:

UnboundLocalError: local variable 'total' referenced before assignment
Run Code Online (Sandbox Code Playgroud)

在文件的开头(在出现错误的函数之前),我使用global关键字声明'total'.然后,在程序的主体中,在调用使用'total'的函数之前,我将它指定为0.我已经尝试在各个地方将它设置为0(包括文件的顶部,就在它被声明之后) ),但我不能让它工作.有谁看到我做错了什么?

python

62
推荐指数
2
解决办法
15万
查看次数

从父函数赋值给变量:"赋值前引用的局部变量"

对于以下Python 2.7代码:

#!/usr/bin/python

def funcA():
   print "funcA"
   c = 0 
   def funcB():
      c += 3
      print "funcB", c

   def funcC():
      print "funcC", c

   print "c", c
   funcB()
   c += 2
   funcC()
   c += 2
   funcB()
   c += 2
   funcC()
   print "end"

funcA()
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

File "./a.py", line 9, in funcB
    c += 3
UnboundLocalError: local variable 'c' referenced before assignment
Run Code Online (Sandbox Code Playgroud)

但是,当我注释掉该行c += 3funcB,我得到以下的输出:

funcA
c 0
funcB 0
funcC 2
funcB 4
funcC 6
end
Run Code Online (Sandbox Code Playgroud)

c在 …

python

32
推荐指数
2
解决办法
4万
查看次数

标签 统计

python ×3

dynamic-languages ×1

scope ×1