2013-04-25 118 views
0

我已經改變的值 'a' 調用函數get_size()在兩個程序爲什麼這兩個程序會導致不同的結果?

1日前:

a='' 
def get_size(b): 
    size=len(b) 
    return size 

def main(): 
    a='qwerr' 
    print 'the size of a is:',get_size(a) 
if __name__=='__main__': 
    main() 

控制檯:the size of a is: 5


第二:

a='' 

def get_size(): 
    size=len(a) 
    return size 

def main(): 
    a='qwerr' 
    print 'the size of a is:',get_size() 
if __name__=='__main__': 
    main() 

控制檯:the size of a is: 0

回答

1

這是一個範圍問題。第一個方案中的main()局部範圍內產生a,然後傳遞,爲get_size(),而第二個方案從get_size()內引用全局a。如果您希望第二個按預期工作,則需要在main()範圍內使a全局。

main() 
    global a 
    a = 'qwerr' 
    print 'the size of a is:',get_size() 

正如在評論中指出,一個main() -scoped a在兩個版本中創建的,但由於在版本get_size() 1個引用全球a,設置在main()當地a沒有任何影響什麼get_size()上運行。

真的不過,你應該儘量不使用全局變量,部分是爲了避免恰好遇到這裏的歧義。

+0

在*雙向*程序, 'main'創建一個本地'a'。 – delnan 2013-04-25 17:25:40

+0

@delnan是的,但由於'get_size()'在第一個版本中使用全局的'a',所以這個事實並不重要。我會嘗試更新我的答案的措辭以澄清。 – 2013-04-25 17:27:27

+0

謝謝大家 – ray 2013-04-25 17:40:34

1

在第一個節目,你是在全局範圍內設置,然後重置爲在DEF範圍主要另一個字符串。

+0

我認爲在main()中創建的作用域是gloal.thank你 – ray 2013-04-25 17:42:22

0

在第二個方案,get_size方法將檢查在其本地範圍「A」值,但因爲它是不存在的,在它的局部範圍內,然後它會驗證它是全球範圍內

相關問題