为什么全局变量是邪恶的? [英] Why are global variables evil?

查看:132
本文介绍了为什么全局变量是邪恶的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一个很好的源代码,解释了为什么在Python中(以及在编程中)使用 global 被认为是不好的做法。有人可以指给我一个或在这里解释吗?

解决方案

这与Python无关;全局变量在任何编程语言中都是不好的。



然而,全局常量在概念上与全局变量 ;全局常量使用起来很不错。它只是在Python中没有语法上的差异。



它们不好的原因是它们允许函数隐藏(如非明显和未声明),因此很难理解副作用。此外,这可能会导致意大利面代码

另外,全局变量的有限/受控/有意识的使用是可以接受的,就像本地状态,即可变变量,在函数编程中可接受的一样,无论是出于性能原因还是简单性,还是用于缓存/记忆。
$ b

但是当然,你的问题有很多答案,所以你最好的选择就是google为什么全局变量不好。一些例子:



如果您想深入了解并了解为什么会出现副作用以及其他许多启发性的问题,您应该学习函数式编程:


I was trying to find a good source that explains why the use of global is considered to be bad practice in python (and in programming in general). Can somebody point me to one or explain here?

解决方案

This has nothing to do with Python; global variables are bad in any programming language.

However, global constants are not conceptually the same as global variables; global constants are perfectly fine to use. It's just that in Python there is no syntactic difference.

The reason they are bad is that they allow functions to have hidden (as in "non-obvious" and "undeclared") and thus hard to understand side effects. Also, this can lead to Spaghetti code.

Also, limited/controlled/conscious use of globals is acceptable, just as local state, i.e. mutable variables, is acceptable in Functional Programming, either for performance reasons or simplicity, or for caching/memoization.

But of course, your question has many answers, so your best bet is to just google "why are global variables bad". Some examples:

If you want to go deeper and find out why side effects are all about, and many other enlightening things, you should learn Functional Programming:

这篇关于为什么全局变量是邪恶的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆