我读到一个关于Python全局语句( "Python scope" )的问题,我想起了我在Python初学者时使用这个语句的频率(我经常使用全局语句),几年后的今天,我根本就不使用它了。我甚至认为这有点“非pythonic”。
在Python中使用此语句吗?你对它的使用随着时间的推移而改变了吗?
发布于 2008-09-28 23:23:53
我在这样的上下文中使用'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
发布于 2008-09-28 19:39:09
在我从事3+多年的专业使用和五年多的Python爱好者生涯中,我从未在任何生产代码中合法地使用过该语句。我需要更改的任何状态都驻留在类中,或者,如果存在某种“全局”状态,它就驻留在某个共享结构中,比如全局缓存。
发布于 2011-06-29 23:38:29
我曾在函数创建或设置全局使用的变量时使用过它。下面是一些示例:
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
https://stackoverflow.com/questions/146557
复制相似问题