如何在mainloop函数中获取Accessme的值?
def example():
test=True
while test:
print("some stuff")
if test2==True:
Accessme = 400 # Need to access this
print("some stuff")
if test3==True:
print("some stuff")
mainloop(x,y)
elif test2==False:
print("some stuff")
def mainloop(x,y):
cheese = 1
noise = []
for something in somecodehere:
print("some stuff")
output = some more code here
print("some stuff",Accessme ) #Calling from here
这是我得到的错误:
> NameError: name 'Accessme' is not defined
答案 0 :(得分:3)
你的示例代码很乱,所以我简化了以便你理解这个概念:
def example():
test=True
while test:
Accessme = 400 #Assign the variable
break
return Accessme #This will return the variable. Accessme is local to the function example and nowhere else.
def mainloop(x=0,y=0):
cheese = 1
noise = []
print("some stuff",example() ) #You can grab the output from example by calling the function example, not Accessme.
mainloop()
我建议你阅读Scope。您的问题是Accessme不在mainloop的范围内。
答案 1 :(得分:1)
如果您想要访问Accessme
是全局的(即,在任何特定函数之外),那么您需要告诉每个函数这种情况:
global Accessme
使用全局变量通常是糟糕的。如果您想从函数中获取信息,最好返回该信息,就像将信息输入函数最好通过参数完成。