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
_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
我曾在函数创建或设置全局使用的变量的情况下使用过它。下面是一些例子:
或者
在我3年多专业使用Python的时间里,作为一个Python爱好者,我从未在任何生产代码中合法使用过这个语句。我需要更改的任何状态都存在于类中,或者,如果存在某种“全局”状态,则它位于某个共享结构(如全局缓存)中。
我在这样的上下文中使用“global”:
我使用“global”是因为它是有意义的,并且读者可以清楚地了解正在发生的事情。我也知道有这样一种模式,它是等价的,但是给读者带来了更多的认知负担:
相关问题 更多 >
编程相关推荐