全局变量使用

2024-04-20 08:31:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个基本的问题,我在xml函数中声明xmlfile为global,我能在另一个子例程中使用它而没有任何问题吗?子程序的顺序重要吗?你知道吗

 def xml():

        global xmlfile
        file = open('config\\' + productLine + '.xml','r')
        xmlfile=file.read()
 def table():
            parsexml(xmlfile)

Tags: 函数config声明read顺序deftablexml
2条回答

首先,我完全同意其他关于避免全局变量的评论。你应该从重新设计开始避免它们。但要回答你的问题:

子例程的定义顺序无关紧要,调用它们的顺序无关紧要:

>>> def using_func():
...   print a
... 
>>> using_func()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in using_func
NameError: global name 'a' is not defined
>>> def defining_func():
...   global a
...   a = 1
... 
>>> using_func()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in using_func
NameError: global name 'a' is not defined
>>> defining_func()
>>> using_func()
1

函数的编写顺序无关紧要。 xmlfile的值将由调用函数的顺序决定。你知道吗

但是,通常最好避免将值重新分配给函数内部的全局变量,因为这样会使分析函数的行为更加复杂。最好使用函数参数和/或返回值(或者使用类并使变量成为类属性):

def xml():
    with open('config\\' + productLine + '.xml','r') as f:
        return f.read()

def table():
     xmlfile = xml()
     parsexml(xmlfile)

相关问题 更多 >