[英]global statement isn't working, and I don't understand why
I'm a beginner in this area and I'm having trouble finding the same cases to my question.我是这个领域的初学者,我很难找到与我的问题相同的案例。 My code is like this:
我的代码是这样的:
def zerofunc(value):
global g
value = 0
g = 15
zerofunc(g)
print(g)
I set the g to global inside the function to produce 0 as the final result, but it still prints out 15 instead of 0. Could anybody explain why the global statement is not working in this case, and what I should do to avoid the same mistake?我在 function 中将 g 设置为 global 以产生 0 作为最终结果,但它仍然打印出 15 而不是 0。谁能解释为什么 global 语句在这种情况下不起作用,以及我应该做些什么来避免同样的情况错误?
Your function sets a variable named value
to zero, leaving g untouched.您的 function 将名为
value
的变量设置为零,而 g 保持不变。 If you want to change, g
, this code would do it:如果您想更改
g
,此代码将执行此操作:
def zerofunc(value):
global g
g = 0
g = 15
zerofunc(g)
print(g)
That being said, there doesn't appear to be a good reason to make g
global;话虽如此,似乎没有充分的理由让
g
全球化。 globals are generally discouraged.通常不鼓励全局变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.