本文介绍了您是否使用“全局" Python中的语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关Python global 语句的问题("Python作用域" ),我想起了我是Python初学者时使用该语句的频率(我经常使用 global ),以及如今几年后,我如何不再使用它,曾经.我什至认为它有点非pythonic".

I was reading a question about the Python global statement ( "Python scope" ) and I was remembering about how often I used this statement when I was a Python beginner (I used global a lot) and how, nowadays, years later, I don't use it at all, ever. I even consider it a bit "un-pythonic".

您是否在Python中使用此语句?您对它的使用是否随时间而改变?

Do you use this statement in Python ? Has your usage of it changed with time ?

推荐答案

我在诸如此类的上下文中使用'global':

I use 'global' in a context such as this:

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

    # ... figure out result

    _cached_result = result
    return result

我使用全局"是因为它很有意义,并且函数的读者可以清楚了解正在发生的事情.我也知道有这种模式,它是等效的,但是给读者带来了更多的认知负担:

I use 'global' because it makes sense and is clear to the reader of the function what is happening. I also know there is this pattern, which is equivalent, but places more cognitive load on the reader:

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

    # ... figure out result

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

这篇关于您是否使用“全局" Python中的语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:03