Advertisement
elena1234

Closure ( Python )

Jan 24th, 2022
734
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. def outer():
  2.     x = 'local'
  3.  
  4.     def inner():
  5.         nonlocal x
  6.         x = 'nonlocal'
  7.         print('inner:', x)
  8.  
  9.     inner()
  10.     print('outer', x)
  11.  
  12.  
  13. outer()
  14.  
  15. # Another example for Closure
  16. def getFibonator():
  17.     prevNum = 0
  18.     currentNum = 1
  19.  
  20.     def inner():
  21.         nonlocal prevNum, currentNum
  22.         nextNum = prevNum + currentNum
  23.         prevNum = currentNum
  24.         currentNum = nextNum
  25.         return (prevNum)
  26.  
  27.     return inner
  28.  
  29.  
  30. counter = getFibonator()
  31. print(counter())
  32. print(counter())
  33. print(counter())
  34. print(counter())
  35. print(counter())
  36.  
  37.  
  38. # Another example for Closure
  39. def sum():
  40.     number = 0
  41.  
  42.     def inner():
  43.         nonlocal number
  44.         number += 1
  45.         return (number)
  46.  
  47.     return inner
  48.  
  49.  
  50. new_counter = sum()
  51. print(new_counter())
  52. print(new_counter())
  53. print(new_counter())
  54.  
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement