Apologies, somewhat confused Python newbie question. 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 instantiate a dog first?
I guess my question is, is there any difference? In the second example, does initiating the dog create a module level globvar just like in the first example, that will behave the same and have the same scope?
globaldoesn’t create a new variable, it just states that this name should refer to a global variable instead of a local one. Usually assignments to variables in a function/class/… refer to local variables. For example take a function like this:Here a new local variable
mis created, even if there might be a global variablemalready existing. This is what you usually want since some function call shouldn’t unexpectedly modify variables in the surrounding scopes. If you indeed want to modify a global variable and not create a new local one, you can use theglobalkeyword:In your case
globalin the constructor doesn’t create any variables, further attempts to accessglobvarfail:But if you would actually assign a value to
globvarin the constructor, a module-global variable would be created when you create a dog:Execution: