|
|
Python Variable scope gymnasticsFrom $1Table of contentsI have been having some problem with python variable scope . It all boils down to the question , does python treat give class variables as having an instance scope while at the same time class arrays and class dicts have class scope. If all this sounds confusing look at this example code #!/usr/bin/env python You will notice if you run this example you get the variable classvar behaving as an instance var i.e p.classvar and p2.classvar are different. #commandline>python testclassvars.py p2 name is: Smart p name is i am set for p p2 classvar is now None And p classvar is i am set for p Are python arrays in a class scopeNow take the same examples and replace classvar with an array and change the mutate method to append to the array. So the code now becomes #!/usr/bin/env python And when we run this we can see that the array classvar is now in the class scope. i.e every instance of that class shares the same classvar array. Running the code gives #commandline>python testclassvars.py p2 name is: Smart p name is i am set for p p2 classvar is now ['i am set for p'] And p classvar is ['i am set for p']
Funky isnt it. It turns out dictionaries also seem to have the same scope i.e class scope.
Tags:
|