Global variables
If a variable is defined at a module level and if it is desired to change it inside a function,
then Python requires a ‘global’ statement in the function to get hold of the variable from
outside. For example, suppose we have a counter that is incremented inside a function,
then we could do
counter = 0
def someFunction(argument):
global counter
counter += 1
performOperation(argument)
In some ways it is good that Python has this arduous way of modifying variables
defined at module level, because it is generally not a good idea to code this way. Often
you would avoid using global entirely by passing variables in as arguments and collecting
them as output:
counter = 0
def someFunction(argument, counterVal):
counterVal += 1
performOperation(argument)
return counterVal
counter = someFunction(input, counter)
Do'stlaringiz bilan baham: |