在Python中使用“global”语句吗?

2024-04-26 01:11:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我读到了一个关于Pythonglobal语句("Python scope")的问题,我记得我在Python初学者的时候经常使用这个语句(我经常使用global语句),以及多年后的今天,我是如何完全不用它的。我甚至认为它有点“非Python”

你在Python中使用这个语句吗?你对它的使用随时间改变了吗?


Tags: 时间语句globalscope初学者pythonglobal
3条回答

我曾在函数创建或设置全局使用的变量的情况下使用过它。下面是一些例子:

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
...

或者

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

在我3年多专业使用Python的时间里,作为一个Python爱好者,我从未在任何生产代码中合法使用过这个语句。我需要更改的任何状态都存在于类中,或者,如果存在某种“全局”状态,则它位于某个共享结构(如全局缓存)中。

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

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

    # ... figure out result

    _cached_result = result
    return result

我使用“global”是因为它是有意义的,并且读者可以清楚地了解正在发生的事情。我也知道有这样一种模式,它是等价的,但是给读者带来了更多的认知负担:

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

    # ... figure out result

    myComputationallyExpensiveFunction.cache = result
    return result
myComputationallyExpensiveFunction.cache = None

相关问题 更多 >