1

我有一个基本问题,我在 xml 函数中将 xmlfile 声明为全局,我可以在另一个子例程中使用它而没有任何问题吗?子例程的顺序重要吗?

 def xml():

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

2 回答 2

2

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

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

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

def table():
     xmlfile = xml()
     parsexml(xmlfile)
于 2012-11-10T18:48:19.413 回答
0

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

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

>>> 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
于 2012-11-10T18:48:17.993 回答