global does not create a new variable, it simply indicates that this name should refer to a global variable instead of a local one. Typically, variable assignments in a function / class / ... refer to local variables. For example, execute the following function:
def increment(n)
A new local variable m is created here, even if an existing global variable m exists. This is what you usually want, as some function calls should not unexpectedly change variables in surrounding areas. If you really want to change the global variable, rather than create a new local one, you can use the global :
def increment(n) global increment_calls increment_calls += 1 return n+1
In your case global , no variables are created in the constructor; further attempts to access globvar not made:
>>> import animals >>> d = animals.dog() >>> d.bark() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "animals.py", line 7, in bark print globvar NameError: global name 'globvar' is not defined
But if you really globvar value in the constructor, creating a dog will create a global-global variable:
class dog: def __init__(self): global globvar globvar = 1 ...
Execution:
>>> import animals >>> d = animals.dog() >>> d.bark() 1 >>> print animals.globvar 1
source share