![](/img/trans.png)
[英]how can I change the global variable in each function without the functions affecting each other in Python?
[英]How do I create a variable in a function that other functions can access in python?
如何使一個函數可以訪問另一個這樣的變量?
>>> 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
即使我將pop
分配為1
這似乎也會引發UnboundLocalError
。 為什么是這樣?
這聽起來像是上課的情況。
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()
您可以使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.