智慧大石
考虑以下代码:a = 1def f(): # uses global because it hasn't been rebound print 'f: ',adef g(): # variable is rebound so global a isn't touched a = 2 print 'g: ',adef h(): # specify that the a we want is the global variable global a a = 3 print 'h: ',aprint 'global: ',af()print 'global: ',ag()print 'global: ',ah()print 'global: ',a输出:global: 1f: 1global: 1g: 2global: 1h: 3global: 3基本上,当您需要每个函数访问同一变量(对象)时,都使用全局变量。不过,这并不总是最好的方法。