Skip to main content
 首页 » 编程设计

python之如何在其他函数可以在 python 中访问的函数中创建变量

2025年05月04日16me-sa

如何使一个函数可以像这样访问另一个变量?

>>> 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()