如何使一个函数可以像这样访问另一个变量?
>>> def foo():
... pop = 1
... print pop
...
>>> def oof():
... pop-=1
... print pop
...
>>> foo()
1
>>> oof()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in oof
UnboundLocalError: local variable 'pop' referenced before assignment
这似乎引发了一个 UnboundLocalError
,即使我已将 pop
分配给 1
。这是为什么?
最佳答案
这听起来像是 class 的情况.
class Bar:
pop=0
def foo(self):
self.pop=1
print(self.pop)
def oof(self):
self.pop-=1
print(self.pop)
bar=Bar()
bar.foo()
bar.oof()
关于python - 如何在其他函数可以在 python 中访问的函数中创建变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21613126/