繁体   English   中英

为什么全局变量在Python中的不同函数中不起作用?

[英]Why the global variable is not working in the different functions in Python?

我是Python的新手。 我写了如下代码,只是为了练习。

i=1
def wrte():
 global i
 while i<5:
     print "%s .Line..\n" %i
     i+=1

def appnd():
  j=i
  while i in range(i,j+3):
     print "%s .Line..\n" %i
     i+=1

def Main():
   wrte()
   appnd()

Main()

输出如下

  1 .Line..

    2 .Line..

    3 .Line..

    4 .Line..

**Traceback (most recent call last):
  Line 18, in <module>
    Main()
  Line 16, in Main
    appnd()
  Line 9, in appnd
    j=i
UnboundLocalError: local variable 'i' referenced before assignment**

预期结果::下一个序列应该像

5. Line..
6. Line..
7. Line..

请帮助我。

在使用该变量的每个函数中都需要global定义。

def appnd():
   global i

注意:如果可能,请将全局变量和相关函数移到类中。

global i

之前

j=i

应该解决问题

您的定义范围是本地的。 如果您在函数中将变量声明为全局变量,并不意味着它将应用于所有函数。 您还必须在appnd()函数中将i声明为全局变量。 话虽如此,这并不意味着您的风格是正确的。 您宁愿将变量传递给函数。

下一个定义将起作用:

def appnd():
  j=i
  while i in range(i,j+3):
     print "%s .Line..\n" %i

# it would print infinitely, but will work

在编译时,Python会查看函数中使用变量的方式,以定义查找它们的范围。 在您对appnd的定义中,它会看到为i分配的值,因此试图将其威胁为局部变量。 在我的代码中没有赋值,因此Python只是从父级作用域获取i的值-在这种情况下, i既不是本地的也不是全局的,它称为free variable 执行模型-范围和绑定 -强烈建议阅读。

我想您知道何时应该使用全局,否则它将不在您的写入函数中。 如果仅读取变量,可以忽略它,我想在您的append函数中需要该变量,但是其中有i + = 1,因此可以对其进行修改。 只需更改追加即可:

for line in range(i, i + 3):
    print "%s .Line..\n" % line

appnd函数中,必须使全局变量i

i=1
def wrte():
 global i
 while i<5:
     print "%s .Line..\n" %i
     i+=1

def appnd():
    global i
    j=i
    while i in range(i,j+3):
        print "%s .Line..\n" %i
        i+=1

def Main():
   wrte()
   appnd()

Main()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM