有没有办法在子函数和父函数之间交换不是列表的变量?
#parent
list=[0]*1
singlevalue = 0
#child - 0
def test():
list[0]= list[0]+1
return list
#parent
test() #>>1
test() #>>2
#child - 1
def test():
singlevalue = singlevalue +1
return singlevalue
#parent
test() >>
# singlevalue = singlevalue +1
#UnboundLocalError: local variable 'singlevalue' referenced before assignment
该示例向您展示了 list 输出 1 并保留它以供下次执行。 为什么单值有不同的方式?
最佳答案
到目前为止,两个答案都提出了一个解决方案,但这不是帖子的重点。不同之处在于,对于列表,您正在使用引用,而不是像处理单值
那样操作“绑定(bind)”变量。
例如,一旦您尝试执行:l = l + [1]
,您就会尝试修改绑定(bind)的l
并得到相同的错误。这是因为 python 中的作用域是如何工作的!
简而言之:
singlevalue [local variable] = singlevalue [actually a global variable but access to locally stored variable] + 1 [constant]
单值存储在本地。现在它想要访问本地存储的变量,该变量还没有值,因为它还没有被分配。如果您想将其存储在全局范围内,则需要使用 global
关键字。
list[0] [slot in a referenced list] = list[0] [still same slot, which has a value already]+1
因此,没问题。 :)
更多详细信息:
我们可以在这里查看 python 的字节码,看看加载方面的差异:
>>> def m():
... y = 1
... def test():
... y = y + 1
... return y
... test()
>>> m()
UnboundLocalError: local variable 'y' referenced before assignment
>>> dis.dis(m)
[... cur here ... Inside of test()]
# <-- here the value of the constant is loaded from the local namespace
3 6 LOAD_CONST 2 (<code object test at 02A067B8, file "<pyshell#33>", line 3>)
9 MAKE_FUNCTION 0
12 STORE_FAST 1 (test)
[... cut here ...]
>>> def l():
... li = [1]
... def test():
... li[0] = li[0] + 1
... return li
... test()
>>> l()
[... cut here ... Inside of test()]
# <-- here a reference is loaded!
3 9 LOAD_CLOSURE 0 (li)
12 BUILD_TUPLE 1
15 LOAD_CONST 2 (<code object test at 02A06698, file "<pyshell#28>", line 3>)
18 MAKE_CLOSURE 0
21 STORE_FAST 0 (test)
[... cut here ...]
由于这篇文章会变得太长,我建议执行上面的命令并查看这里:http://docs.python.org/2/library/dis.html看看差异!
然而,存储方式的主要区别发生在第一个 block 中:
2 0 LOAD_CONST 1 (1)
3 STORE_FAST 0 (y) # <- push loaded constant to stack
2 0 LOAD_CONST 1 (1)
3 BUILD_LIST 1
6 STORE_DEREF 0 (li) # <- stores the value in the list
看看here !
我希望这有助于消除差异。干杯!
关于python 函数之间的单个整型变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17142544/