你在Python中使用“global”语句吗? [关闭]

2023-12-03

我正在读一个关于Python的问题global陈述 (“Python 范围”),我记得当我还是一个 Python 初学者时,我经常使用这个语句(我使用过global很多)以及如何,现在,几年后,我根本不再使用它。我什至认为它有点“非Pythonic”。

你在Python中使用这个语句吗?随着时间的推移,你对它的使用有变化吗?


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

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

    # ... figure out result

    _cached_result = result
    return result

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

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

    # ... figure out result

    myComputationallyExpensiveFunction.cache = result
    return result
myComputationallyExpensiveFunction.cache = None
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

你在Python中使用“global”语句吗? [关闭] 的相关文章

随机推荐