你在Python中使用"全局"语句吗?

Aur*_*oni 63 python global

我正在阅读有关Python 全局语句("Python范围")的问题,我记得当我是Python初学者时我经常使用这个语句(我使用全局))以及如何,如今,多年后,我不知道永远不要使用它.我甚至认为它有点"非pythonic".

你在Python中使用这个语句吗?您对它的使用是否随时间而变化?

Jer*_*rub 56

我在这样的上下文中使用'global':

_cached_result = None
def myComputationallyExpensiveFunction():
    global _cached_result
    if _cached_result:
       return _cached_result

    # ... figure out result

    _cached_result = result
    return result
Run Code Online (Sandbox Code Playgroud)

我使用'全局'是因为它有意义并且对于函数的读者来说很清楚发生了什么.我也知道这种模式是等效的,但会给读者带来更多的认知负担:

def myComputationallyExpensiveFunction():
    if myComputationallyExpensiveFunction.cache:
        return myComputationallyExpensiveFunction.cache

    # ... figure out result

    myComputationallyExpensiveFunction.cache = result
    return result
myComputationallyExpensiveFunction.cache = None
Run Code Online (Sandbox Code Playgroud)

  • 我倾向于在这样的实例中使用装饰器模块的'memoize'功能,但我不能错过你全局使用的清晰度:) (15认同)
  • 我不知道定义函数属性的可能性,例如myComputationallyExpensiveFunction.cache并在函数体内使用它,谢谢! (6认同)
  • 第二个例子的第二行应该是"if getattr(myComputationallyExpensiveFunction,"cache",None):",否则是AttributeError. (5认同)
  • 我从未听说过为函数赋值,这是很棒的东西!谢谢! (2认同)

iro*_*ggy 15

在我3年多的专业使用Python以及作为Python业余爱好者超过5年的任何生产代码中,我从来没有合法使用过该语句.我需要更改的任何状态都驻留在类中,或者,如果存在某种"全局"状态,它就位于某个共享结构中,如全局缓存.


小智 10

我已经在函数创建或设置将在全局使用的变量的情况下使用它.这里有些例子:

discretes = 0
def use_discretes():
    #this global statement is a message to the parser to refer 
    #to the globally defined identifier "discretes"
    global discretes
    if using_real_hardware():
        discretes = 1
...
Run Code Online (Sandbox Code Playgroud)

要么

file1.py:
    def setup():
        global DISP1, DISP2, DISP3
        DISP1 = grab_handle('display_1')
        DISP2 = grab_handle('display_2')
        DISP3 = grab_handle('display_3')
        ...

file2.py:
    import file1

    file1.setup()
    #file1.DISP1 DOES NOT EXIST until after setup() is called.
    file1.DISP1.resolution = 1024, 768
Run Code Online (Sandbox Code Playgroud)


ken*_*der 8

在我看来,只要你觉得需要在python代码中使用全局变量,现在是停下来并重新编写代码的好时机.如果你的死线很接近,
那么global放入代码并推迟重构过程可能听起来很有希望,但是,相信我,你不会回到这个并修复除非你真的必须 - 就像你的代码停止工作一些奇怪的是,你必须调试它,你会遇到一些global变量,他们所做的只是弄乱了.

所以,老实说,即使是允许的,我也会尽量避免使用它.即使它意味着一个简单的类 - 围绕你的代码构建.