Python Variable scope gymnastics

From $1

I 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
#coding=utf-8


class hari(object):
    classvar = None
    def __init__(self,name):
        self.name = name
    def mutate(self,name):
        self.classvar = name
        self.name = name


def main():
    p = hari("Smart")
    p2 = hari("Smart")
    p.mutate("i am set for p")
    print "p2 name is:" , p2.name
    print "p name is " , p.name
    print "p2 classvar is now",p2.classvar,"And p classvar is ",p.classvar 
   

if __name__ == "__main__":
    main()

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 scope

Now 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
#coding=utf-8


class hari(object):
    classvar = []
    def __init__(self,name):
        self.name = name
    def mutate(self,name):
        self.classvar.append(name)
        self.name = name


def main():
    p = hari("Smart")
    p2 = hari("Smart")
    p.mutate("i am set for p")
    print "p2 name is:" , p2.name
    print "p name is " , p.name
    print "p2 classvar is now",p2.classvar,"And p classvar is ",p.classvar 
   

if __name__ == "__main__":
    main()
 

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:
 
Images (0)
 
Comments (0)
You must login to post a comment.