daily pastebin goal
55%
SHARE
TWEET

Untitled

a guest Apr 17th, 2018 48 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var=1
  2. class ClassName():
  3.     def __init__(self):
  4.        # ...
  5.     #some other methods that do not need global variable here
  6.  
  7.     def Met():
  8.         #do some other stuff that needs the global var
  9.    
  10. """ Approach one """
  11. var=1
  12. class ClassName():
  13.     def __init__(self):
  14.        # ...
  15.     #some other methods that do not need global variable here
  16.     def Met():
  17.         # needs the global var to operate
  18.         global var
  19.         # do some stuff with var (including editing)
  20.  
  21.  
  22. """ Approach two"""
  23. var=1
  24. class ClassName(var):
  25.     def __init__(self):
  26.        # ...
  27.     #some methods that do not need global variable here
  28.     def Met(var):
  29.         # do some stuff with var (including editing)
  30.    
  31. var=1
  32. def func1():
  33.     #do some stuff
  34.     #do not need global variable here
  35.  
  36.     def func2():
  37.         #do some other stuff
  38.         # need the global var
  39.  
  40.     func2() # call func2
  41.    
  42. var=1
  43. def func1():
  44.     def func2():
  45.         global var
  46.         var = 2       # global variable updated
  47.     func2()
  48. func1()
  49. print(var)
  50.    
  51. var=1
  52. def func1(var):
  53.     def func2(var):
  54.         var = 2
  55.         print(var)    # local var is printed, global var unchanged
  56.     func2(var)
  57. func1(var)
  58. print(var)           # global var is printed
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top