什么是“全局变量不好”意思? [英] What does "global variables are bad" mean?
问题描述
所以我可以从全局变量读取
def f():
print x
我也可以指定它
def g()
global x
x = 3
当人们说全局变量不好时,他们的意思是说阅读和分配都不好,或者只是分配不好? (我的印象是,阅读并不危险)
这个问题不是那么多全局==糟糕 全局可变状态使得很难推断程序流程
为了说明,想象一下这个函数: DEF FROB():
如果my_global:
维布勒()
,否则:
摆动()
也就是说, frob()
的行为取决于状态,或者是 frob()
的主体,也不是任何可能调用它的代码。你要揣摩什么样的变化 my_global
,而当这些变化发生的关于的当 FROB()
被调用。
在编写小脚本时,这不是什么大问题,您可以看到并理解全局的所有地方变量的变化,并且可能在你的头脑中发生变化时以及何时调用相关位。在大型项目中,这是更加努力的工作,以至于全局可变状态被广泛认为是反模式。
So I can read from a global variable
def f() :
print x
And I can also assign it
def g()
global x
x = 3
When people say "global variables are bad", do they mean that both reading and assigning are bad, or just assigning is bad? (my impression is that reading is not dangerous)
The problem is not so much "global == bad" so much as "Global mutable state makes it hard to reason about program flow"
To illustrate, imagine this function:
def frob():
if my_global:
wibble()
else:
wobble()
That is, frob()
s behavior depends on state whos nature is not obvious from either the body of frob()
, nor from any code that might have called it. You have to try to figure out what changes my_global
, and when those changes happen in relation to when frob()
is called.
When programming small scripts, this isn't much of a problem, you can see and understand all of the places that the global variable changes, and probably sort out in your head when it changes and when the dependent bits are invoked. In large programs, that's much more effort, to the point that global mutable state is widely regarded as an anti-pattern.
这篇关于什么是“全局变量不好”意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!