2013-07-05 86 views
0

定義的變量我有一個大的功能,在其內部嵌套的一些功能,如下所示:訪問在功能

def primary(input): 

    def second(): 
     print "something" 

    def third(): 
     treasure = "Success!" 
     print treasure 

第三()函數定義的變量寶並打印。我應該如何改變這個變量的範圍,以便我可以從解釋器打印寶藏,而不必調用任何函數,但仍然允許函數訪問/更改它?

+1

我強烈建議你重新考慮你的代碼的結構,如果這是你所需要的。 –

回答

3

你將不得不使它成爲一個全球性的;函數中的局部變量不可訪問,嵌套或以其他方式。

只是訪問treasure作爲一個全球性的作品就好了:

treasure = "Success!" 

def primary(input): 
    def second(): 
     print "something" 

    def third(): 
     print treasure 

要的功能範圍內改變treasure,聲明其全局與global關鍵字。

treasure = "Success!" 

def primary(input): 
    def second(): 
     print "something" 

    def third(): 
     global treasure 
     treasure = 'changed!' 
     print treasure 

    third() 
0

如果函數third()在寶藏前添加關鍵字「global」。這允許其他功能使用該變量。

還有一種方法可以做到這一點,即在代碼開始時定義var,這看起來好多了,也是我學會如何做到的。

treasure = "Success!" 

def second(): 
    print "Something." 

def third(): 
    print treasure 

third() 

祝你好運。

+0

除非您使用'global'關鍵字,否則您將無法修改變量:>>> treasure =「Success!」 >>> def fourth(): ...寶藏=「島!」 ... >>>第四個() >>>寶藏 '成功!'' – 2rs2ts