different behavior of strings and numbers in python when dealing with class and object variables -


i found 1 issue , not able understand reason of difference:

code1:

class test:     var=2     def __init__(self):         self.var=self.var+1  p=test() print "p.var:",p.var q=test() print "q.var:",q.var 

output 1:

p.var:3 q.var:3 

why not output is(according concept used explain code2)

p.var:3 q.var:4 

code2:

class test:     var=[]     def __init__(self):         self.var.append("fool")  p=test() print "p.var:",p.var q=test() print "q.var:",q.var 

output2:

p.var: ['fool'] q.var: ['fool', 'fool'] 

i read article on code2 in stack exchange: python class instance variables , class variables

but not able link code1 following concept.please help

the difference here lists mutable objects; integers immutable. when code1 increments self.var, must return new object, being 3. on second call,w e start on 2, producing 3 object q.

in code2, var still class object (only 1 class, not 1 per object). when create p, append "fool" empty list. when later create q append second "fool". print them both:

p=test2() print "p.var1:",p.var q=test2() print "q.var2:",q.var print "p.var2:",p.var 

output:

p.var1: ['fool'] q.var2: ['fool', 'fool'] p.var2: ['fool', 'fool'] 

does clarify things?


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -