1 python variables function python-2.7
如何使一个函数可以访问另一个这样的变量?
>>> 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
Run Code Online (Sandbox Code Playgroud)
UnboundLocalError即使我已经分配pop,这似乎也会提高1.为什么是这样?
这听起来像一个班级的案例.
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()
Run Code Online (Sandbox Code Playgroud)