2014-11-25 37 views
0

我可以訪問特定範圍內的其他變量嗎?像這樣:我可以在python3.4中訪問與非本地或全局變量不同的變量嗎?

variable = 'acces with global' 
def function1: 
    variable = 'function 1 variable' 
    def function2: 
     variable = 'I really like this name for variable' 
     def function3: 
      def access_to_local: 
       variable = "it's another variable I can access too!" 
      def access_to_global: 
       global variable 
       variable = 'now I have access to my global variable' 
      def access_to_function2: 
       nonlocal variable 
       variable = 'And easy way to change function2 variable' 
      def access_to_function1: 
       #nonlocal^2 variable? 
       variable = 'And how can I get access to variable in 
          function1?' 

這不是生死問題,我只是好奇心。 我只是在python中學習全局和非本地工作。現在,這絕對夠了,但我想知道我問的是否可能。特別是,我讀到了這一點,他們正在考慮製作一些類似「非特定範圍內的地方」的東西。但他們決定使用非本地。是不是因爲有沒有非本地的做法呢?或者,也許有一些與非本地的技巧,比如寫兩遍nonlocal nonlocal variable

回答

0

不,你不能。沒有辦法指定Python應該跳過一個嵌套的作用域級別。

請注意,使用這種多層次的嵌套並不是真的很自然;如果有的話,你很少會首先使用這種嵌套。如果您需要在這些罕見情況下訪問不同級別的變量,請使用不同的名稱。