Python module global module compared to __init__ globals

Apologies, somewhat embarrassed question to Python newbies. Let's say I have a module called animals.py .......

 globvar = 1 class dog: def bark(self): print globvar class cat: def miaow(self): print globvar 

What is the difference between this and

 class dog: def __init__(self): global globvar def bark(self): print globvar class cat: def miaow(self): print globvar 

Assuming I always create a dog first?

I think my question is, is there any difference? In the second example, does dog initiate the creation of the globvar module globvar in the same way as in the first example, which will behave the same and have the same scope?

+4
source share
2 answers

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) # this creates a new local m m = n+1 return m 

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 
+8
source

No, the global operator only matters when assigning a global variable in a method or function. So __init__ does not matter - it does not create a global one because it does not assign it anything.

+4
source

All Articles