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

时间:2014-02-06 20:16:29

标签: python variables python-2.7 function

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

>>> 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。这是为什么?

2 个答案:

答案 0 :(得分:5)

这听起来像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()

答案 1 :(得分:1)

您可以使用global将变量设为全局:

>>> def foo():
...     global pop
...     pop = 1
...     print pop
...
>>> def oof():
...     global pop
...     pop-=1
...     print pop
...
>>> foo()
1
>>> oof()
0
>>> oof()
-1
>>>

或者您可以接收输入和返回输出,如下所示:

>>> def foo():
...    pop = 1
...    return pop
...
>>> pop = foo()
>>> def oof(pop):
...    pop -=1
...    return pop
...
>>> print pop
1
>>> pop = oof(pop)
    >>> print pop
    0