本文介绍了global,globals(),_ global?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 在Python中使用全局变量通常会引起混乱。其他语言使用 a清除前缀为全局。 *你忘了申报全局 *或者你宣布全局很多或有冲突 *你有一个本地相同的变量名称,并希望保存/加载它 来自/来自同名的全球 *当你添加代码时,全局变量的定义越来越多,除了它们的用例之外,它们的移动越来越多 - >怪事;程序员思维分散 *使用globals()[''xy'']是''stringy non-program-code'' 因此,自从很久以来我经常把更大模​​块的负责人...... _global = sys.modules [__ name __] ....并使用全局仅变量/主要像 def f(y): v = x = _global.x _global.y = y ... 对我来说这个方法整体来说要清晰得多。并且它与自我的明确阐述是一致的。作为Python方法中的常规对象(与其他 语言中的冻结@ $ m _ ...。hacks相比,更加自我类似的方式) 我知道,这个家创建_global创建一个循环引用,但通常 这并不严重,因为模块只在程序结束时卸载。 (旁边的问题:这是否可能阻碍全局对象正确地运行;当所有模块被拉动时,至少gc()运行 退出()) 不知怎的,我错过了一个很好的标准方法,可以在 未分段的方式使用全局变量。你觉得怎么样? 罗伯特Using global variables in Python often raises chaos. Other languages usea clear prefix for globals.* you forget to declare a global* or you declare a global too much or in conflict* you have a local identical variable name and want to save/load itto/from the global with same name* while you add code, the definition of globals moves more and moreapart from their use cases -> weirdness; programmers thinking is fragmented* using globals()[''xy''] is ''stringy non-program-code''Thus, since long time at the head of my bigger modules I often put..._global = sys.modules[__name__]....and use global variables only/mainly likedef f(y):v=x=_global.x_global.y=y...for me this method is much more clear overall. And it is in line withthe clear exposition of "self" as regular object in Python methods (in amuch more self-similiar way compared to frozen @ $ m_... hacks in otherlanguages)I know, this home created _global creates a circular ref, but usuallythis is not serious as modules are unload only at the end of a program.( side question: does this maybe hinder global objects from being__del__''ed correctly; is at least gc() run when all modules are pulledoff at exit() )Somehow I miss a nice standard method for using globals in anunfragmented way everywhere. What do you think?Robert推荐答案 这篇关于global,globals(),_ global?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 09:55
查看更多