Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
还有一个Python变量范围问题_Python_Variables_Scope - Fatal编程技术网

还有一个Python变量范围问题

还有一个Python变量范围问题,python,variables,scope,Python,Variables,Scope,我有以下代码: >>> def f(v=1): ... def ff(): ... print v ... v = 2 ... ff() ... >>> f() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in

我有以下代码:

>>> def f(v=1):
...     def ff():
...             print v
...             v = 2
...     ff()
...
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in f
  File "<stdin>", line 3, in ff
UnboundLocalError: local variable 'v' referenced before assignment
def f(v=1): ... def ff(): ... 印刷品 ... v=2 ... ff() ... >>>f() 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 文件“”,第5行,在f中 文件“”,第3行,ff格式 UnboundLocalError:赋值前引用了局部变量“v”
我确实理解为什么会出现此消息(),但在这种情况下如何使用
v
变量
global v在这种情况下不起作用。

在Python 3.x中,可以使用:

在Python2.x中,没有简单的解决方案。黑客就是把
v
列成一个列表:

def f(v=None):
    if v is None:
        v = [1]
    def ff():
        print v[0]
        v[0] = 2
    ff()

您尚未将v传递给内部函数ff。当您声明它时,它会创建自己的范围。这在python 2.x中应该可以工作:

def f(v=1):
  def ff(v=1):
    print v
    v = 2
  ff(v)

但是对
v=2
的赋值调用在对该函数的其他调用中不会持久化。

为什么不直接将v传递给ff()函数呢?@Rich例如,可以有多个嵌套函数。prhaps
def ff(v=v)
将更接近OP想要的。请注意,第二个是(第二次调用时未提供
v
prints 2)。
def f(v=1):
  def ff(v=1):
    print v
    v = 2
  ff(v)