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)

当人们说“全局变量不好”时,他们是否意味着阅读和分配都很糟糕,或者只是分配是不好的? (我的印象是阅读并不危险)

3 个解决方案

#1


9

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.

也就是说,frob()的行为取决于状态,从frob()的主体和任何可能调用它的代码都不是很明显。你必须试着找出my_global的变化,以及何时发生这些变化与调用frob()的时间有关。

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.

编写小脚本时,这不是什么大问题,您可以看到并理解全局变量发生变化的所有位置,并且可能在它发生变化时以及在调用相关位时对其进行排序。在大型项目中,这需要更多努力,以至于全球可变状态被广泛视为反模式。

更多相关文章

  1. 为什么分配给True / False不能像我期望的那样工作?
  2. numpy无法将值分配给列的一部分
  3. MEMCACHED缓存及状态查看
  4. 使用/proc/meminfo文件查看内存状态信息
  5. linux下如何杀掉D状态进程
  6. Linux网络状态工具ss命令使用详解
  7. 在linux上获取已连接电视的电源状态
  8. linux获取网线插拔状态的实现
  9. mysql--查看mysql状态的常用命令

随机推荐

  1. JavaScript 与 Android 交互
  2. Android(安卓)标题栏上加一个返回按钮 超
  3. (2) Android中Binder调用流程 --- Binder环
  4. Android中的资源分析
  5. Android独特的架构:HAL与Dalvik虚拟机
  6. android 属性系统使用的小问题
  7. Android 3.0,将为对战iPad归来
  8. Android 系列 5.9使用Inkscape创建Androi
  9. android 2.3 从零开始学习—环境的搭建以
  10. Android面试系列2018总结(全方面覆盖Andr