python語法32[global與nonlocal比較]



python引用變量的順序: 當前作用域局部變量->外層作用域變量->當前模塊中的全局變量->python內置變量


一 global

global關鍵字用來在函數或其他局部作用域中使用全局變量。但是如果不修改全局變量也可以不使用global關鍵字。

 

gcount = 0

def global_test():
     print (gcount)
    
def global_counter():
     global gcount
    gcount +=1
     return gcount
    
def global_counter_test():
     print(global_counter())
     print(global_counter())
     print(global_counter())

 

 

二 nonlocal

nonlocal關鍵字用來在函數或其他作用域中使用外層(非全局)變量。

 

def make_counter():
    count = 0
     def counter():
        nonlocal count
        count += 1
         return count
     return counter
    
def make_counter_test():
  mc = make_counter()
   print(mc())
   print(mc())
   print(mc())

 

 

也可以使用generator來實現類似的counter。如下:

def counter_generator():
    count = 0
     while True:
        count += 1
         yield count
    
def counter_generator_test():
   #  below is for python 3.x and works well
  citer = counter_generator(). __iter__()
  i = 0
   while(i < 3) : 
     print(citer. __next__())
    i+=1
  
def counter_generator_test2():  
   # below code don't work
   # because next() function still suspends and cannot exit
   # it seems the iterator is generated every time.
  j = 0
   for iter  in counter_generator():
     while(j < 3) : 
       print(iter)
      j+=1


完! 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM