Advertisement
elena1234

Closure in Python

Feb 8th, 2022 (edited)
1,442
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.42 KB | None | 0 0
  1. def calculator():
  2.     result = 0
  3.    
  4.     def add(x):
  5.         nonlocal result
  6.         result += x
  7.        
  8.     def multiply(x):
  9.         nonlocal result
  10.         result *= x
  11.    
  12.     def get_result():
  13.         return result
  14.        
  15.     return (add, multiply, get_result)
  16.  
  17.  
  18. (add, multiply, get_result) = calculator()
  19. (add1, multiply2, get_result2) = calculator()
  20.  
  21. add(1)
  22. add(2)
  23. multiply(2)
  24. print(get_result())
  25.  
  26.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement