Function - Correct Use Of Global Variables In Python 3

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

Which is the correct use of global variables in Python 3?:

1) Stating global VAR_NAME once in the core script (not within a function) and then simply referring to the variable as VAR_NAME everywhere else

2) Stating global VAR_NAME once within every function that uses the global variable and then simply referring to the variable as VAR_NAME for the rest of the function and within the core script itself

Answers

In the first case the global keyword is pointless, so that is not correct. Defining a variable on the module level makes it a global variable, you don t need to global keyword.

The second example is correct usage.

However, the most common usage for global variables are without using the global keyword anywhere. The global keyword is needed only if you want to reassign the global variables in the function/method.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/9366212/correct-use-of-global-variables-in-python-3

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils