In dem folgenden Programm habe ich versucht, Okt mit verschiedenen Werten in Funktionen zuweisen, und drucken Sie es aus. In outer_function() ordne ich oct = 10 (Zeile 10) zu, was eine private Variable ist. Aber ich füge "global oct" in Zeile 20 hinzu. Also habe ich eine Syntaxwarnung bekommen. Das Seltsame ist, dass ich Zeile 19 als "oct in outer_function 2 = ABC" ausgegeben habe. Diese Linie wird vor globalen Erklärung, ich denke, es sollte 10 10.Python globale Deklaration bricht die vorherige Zeile
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!"
Das Ergebnis bekam ich an der Linie zugewiesen werden soll:
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!
Gilt dies auch für Sie das Verhalten Ihres Programms erklären? –