python - Utilisation de variables globales dans une fonction

Mots clés : pythonglobal-variablesscopepython

meilleur 4 Réponses python - Utilisation de variables globales dans une fonction

vote vote

90

globvar = 0  def set_globvar_to_one():     global globvar    # Needed to modify global copy of globvar     globvar = 1  def print_globvar():     print(globvar)     # No need for global declaration to read value of globvar  set_globvar_to_one() print_globvar()       # Prints 1 
vote vote

83

# sample.py myGlobal = 5  def func1():     myGlobal = 42  def func2():     print myGlobal  func1() func2() 
def func1():     global myGlobal     myGlobal = 42 
vote vote

72

x = 0   # Default value of the 'x' configuration setting 
import config config.x = 1 
import config import mod print config.x 
vote vote

66

>>> import dis >>> def foo(): ...     global bar ...     baz = 5 ...     print bar ...     print baz ...     print quux ...  >>> dis.disassemble(foo.func_code)   3           0 LOAD_CONST               1 (5)               3 STORE_FAST               0 (baz)    4           6 LOAD_GLOBAL              0 (bar)               9 PRINT_ITEM                        10 PRINT_NEWLINE           5          11 LOAD_FAST                0 (baz)              14 PRINT_ITEM                        15 PRINT_NEWLINE           6          16 LOAD_GLOBAL              1 (quux)              19 PRINT_ITEM                        20 PRINT_NEWLINE                     21 LOAD_CONST               0 (None)              24 RETURN_VALUE         >>>  

Questions similaires