我有一个基本问题,我在xml函数中声明xmlfile为全局函数,我可以在没有任何问题的情况下在另一个子函数中使用它吗?子例程的顺序是否重要?全局变量的用法
def xml():
global xmlfile
file = open('config\\' + productLine + '.xml','r')
xmlfile=file.read()
def table():
parsexml(xmlfile)
我有一个基本问题,我在xml函数中声明xmlfile为全局函数,我可以在没有任何问题的情况下在另一个子函数中使用它吗?子例程的顺序是否重要?全局变量的用法
def xml():
global xmlfile
file = open('config\\' + productLine + '.xml','r')
xmlfile=file.read()
def table():
parsexml(xmlfile)
中的功能都写无关紧要的顺序。 xmlfile
的值将由函数的调用顺序决定。
但是,通常最好避免将值重新分配给函数内的全局变量 - 它使分析函数的行为更加复杂。这是更好地使用函数参数和/或返回值,(或者使用一个类,并把这些变量作为类属性):
def xml():
with open('config\\' + productLine + '.xml','r') as f:
return f.read()
def table():
xmlfile = xml()
parsexml(xmlfile)
+ 1。 “全球”几乎总是解决问题的错误。 –
首先,我完全同意关于避免全局变量的其他评论。你应该从重新设计开始避免它们。但是,为了回答你的问题:
的子程序的定义并不重要,在你叫他们做的订单的订货:
>>> 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
你,没错,这仅仅是一个样品code..edited它 – user1795998