2012-11-10 78 views
1

我有一個基本問題,我在xml函數中聲明xmlfile爲全局函數,我可以在沒有任何問題的情況下在另一個子函數中使用它嗎?子例程的順序是否重要?全局變量的用法

def xml(): 

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

你,沒錯,這僅僅是一個樣品code..edited它 – user1795998

回答

2

中的功能都寫無關緊要的順序。 xmlfile的值將由函數的調用順序決定。

但是,通常最好避免將值重新分配給函數內的全局變量 - 它使分析函數的行爲更加複雜。這是更好地使用函數參數和/或返回值,(或者使用一個類,並把這些變量作爲類屬性):

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

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

+ 1。 「全球」幾乎總是解決問題的錯誤。 –

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