简体   繁体   English

全局声明不起作用,我不明白为什么

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM