【问题标题】:Python global declaration breaks the previous linePython 全局声明打破了上一行
【发布时间】: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


    【解决方案1】:

    octglobal 声明是在为 oct 赋值之前还是之后都没有关系。这里oct 将是整个函数的全局名称。它不能暂时是局部变量,后来变成全局变量。您会收到语法警告,因为将 global 语句作为函数中的第一件事是非常好的做法。

    要自己检查,请将print locals() 添加到您的函数中:

    def outer_function():
        oct = 10
        print locals()
    

    现在,运行您的程序。它将打印:

    {}

    这意味着没有本地人。所以第 10 行的oct = 10 没有创建一个 局部变量,因为第 20 行中的 global oct

    现在,注释掉 global 语句

    print "oct in outer_function 2 =", oct
    #global oct
    

    再次运行您的程序。它将打印:

    {'oct': 10}
    

    现在您已经在第 10 行创建了一个局部变量。

    【讨论】:

    • 这是否向您解释了您的程序的行为?
    猜你喜欢
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 2012-10-04
    • 2016-03-27
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多