1

I found one issue and not able to understand the 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 the output is(According to concept used to 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 the article on code2 in Stack Exchange: python class instance variables and class variables

but not able to link code1 with the following concept.Please help

Community
  • 1
  • 1
Arnab Mukherjee
  • 190
  • 3
  • 18
  • This has nothing to do with "strings and numbers". In the first piece of code you have an integer, which you replace; in the second, you have a list, on which you call `append`. These are fundamentally different operations, so it shouldn't surprise you that they have different effects, surely? – Daniel Roseman Jan 27 '16 at 18:24
  • I think he's curious as to why `q.var` is 3 and not 4. – wpercy Jan 27 '16 at 18:29
  • thanks Daniel,i have one confusion, why the output is not 3 and 4 in first case, or the class variable is not updated in first case but it is in the second one? – Arnab Mukherjee Jan 27 '16 at 18:31
  • @wilbur that is what i need to know..thank u.. – Arnab Mukherjee Jan 27 '16 at 18:32

1 Answers1

1

The difference here is that lists are mutable objects; integers are immutable. When code1 increments self.var, it must return a new object, that being 3. On the second call,w e start over with 2, producing another 3 for object q.

In code2, var is still a class object (only one for the class, not one per object). When we create p, we append "fool" to the empty list. When we later create q we append a 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 that clarify things?

Prune
  • 76,765
  • 14
  • 60
  • 81
  • 1
    The difference isn't just about whether the data types are mutable. If the list example had done `self.var = self.var + ['fool']`, it would have behaved the same as the first example. Also, a proper explanation of what's going on should really cover how the first example creates instance attributes that hide the class attribute. – user2357112 Jan 27 '16 at 18:48
  • Thanks @user2357112 for your reply, can u please explain little more? – Arnab Mukherjee Jan 27 '16 at 18:52