【发布时间】:2016-04-21 04:09:31
【问题描述】:
在下面的程序中,我尝试在函数内部为 oct 分配不同的值,并打印它。在 outer_function() 中,我分配了 oct = 10(第 10 行),这是私有变量。但是我在第 20 行添加了“global oct”。所以我得到了一个语法警告。虽然奇怪的是我得到了第 19 行的输出为“outer_function 2 = ABC 中的 oct”。这一行是在全局声明之前,我觉得应该在第10行赋值为10。
1 #! /usr/bin/env python
2
3 """
4 Program: function_scope.py
5 Function: Program for working through scope rules
6
7 """
8
9 def outer_function():
10 oct = 10
11 print "oct in outer_function 1 =", oct
12 def inner_function():
13 global oct
14 oct = "ABC"
15 print "oct in inner_function =", oct
16
17
18 inner_function()
19 print "oct in outer_function 2 =", oct
20 global oct
21 #del oct
22
23 oct = 0
24 print "oct in module before =", oct
25
26 outer_function()
27
28 print "oct in module after =", oct
29
30 print "That's all folks!"
我得到的结果是:
In [245]: run ch05_03_function_scope.py
/home/sherlock/Desktop/IntroductionPython/Ch05_functions/ch05_03_function_scope.py:20: SyntaxWarning: name 'oct' is assigned to before global declaration
global oct
oct in module before = 0
oct in outer_function 1 = 10
oct in inner_function = ABC
oct in outer_function 2 = ABC
oct in module after = ABC
That's all folks!
【问题讨论】:
标签: python python-2.7 scope global