简体   繁体   English

python全局变量麻烦

[英]python global variable trouble

I am having troubles using global variables in python... 我在python中使用全局变量时遇到麻烦...

In my program, i have declared 2 global variables, global SYNC_DATA and global SYNC_TOTAL_SIZE 在我的程序中,我声明了2个全局变量,全局SYNC_DATA和全局SYNC_TOTAL_SIZE

Now in one of my functions, I am able to use the global variable SYNC_DATA without declaring it as global again in the function; 现在在我的一个函数中,我可以使用全局变量SYNC_DATA,而无需在函数中再次将其声明为全局变量。 however , I am not able to use the other global variable SYNC_TOTAL_SIZE in the same way. 但是,我不能以相同的方式使用其他全局变量SYNC_TOTAL_SIZE。 I have to declare the latter as global in the function again to use it. 我必须再次在函数中将后者声明为全局函数才能使用它。 I get this error if i use it without declaring as global in the function - "UnboundLocalError: local variable 'SYNC_TOTAL_SIZE' referenced before assignment" 如果我在函数中未声明为全局变量而使用它,则会收到此错误-“ UnboundLocalError:分配前引用了局部变量'SYNC_TOTAL_SIZE'”

Why is it so that sometimes I can access global variables without declaring them as global in functions and sometimes not? 为什么这样,有时我可以访问全局变量而无需在函数中将它们声明为全局变量,而有时却不能? And why Is it that we have to again declare it as global in the function when it is already declared once in the beginning... Why doesn`t the function just check the variable in the global namespace if it does not find it in its namespace directly? 以及为什么在开始就已经声明过一次之后,我们又必须在函数中再次将其声明为全局变量呢?直接命名空间?

Assuming SYNC_TOTAL_SIZE is not declared as local variable. 假设未将SYNC_TOTAL_SIZE声明为局部变量。 It depends on what operations you are performing on global variables, for just reading the global variable there is no need to declare it as global, but if you are modifying the value of global variable you have to declare it with global . 这取决于您对全局变量执行的操作,仅读取全局变量就无需将其声明为全局变量,但是如果您要修改全局变量的值,则必须使用global声明它。

Because SYNC_TOTAL_SIZE is probably used somewhere else in that code as non-global, which makes Python find it and think it isn't global. 因为SYNC_TOTAL_SIZE可能在该代码的其他地方用作非全局SYNC_TOTAL_SIZE ,这使Python可以找到它并认为它不是全局SYNC_TOTAL_SIZE Another reason may be that you just read it in some function and so it doesn't need a global declaration (see this question for more details). 另一个原因可能是您只是在某个函数中读取了它,因此它不需要global声明(有关更多详细信息,请参见此问题 )。 For an exact diagnosis, post a minimal code snippet that demonstrates your problem. 为了进行准确的诊断,请发布一个最小的代码片段来演示您的问题。

The advice is to always say global when you mean it. 建议是在您要说的时候总是说global

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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