2

I have simple class written

class Test:

    stat = 0

    def __init__(self):
        self.inst = 10

    def printa(self):
        print Test.stat
        print self.inst

Now I've created two object of this class

$ a = Test()
$ b = Test()

When I say a.printa() or b.printa() it outputs 0 10 which is understandable.

But when I say

$ a.stat = 2
$ print a.stat

It'll output

2

But when I say a.printa() It'll output

1
10

What's the difference between saying objInstance.staticVar and ClassName.staticVar?? What it is doing internally?

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
Ganesh Satpute
  • 3,664
  • 6
  • 41
  • 78
  • While the same mechanism is being discussed, this is not a duplicate of [Static class variables in Python](http://stackoverflow.com/questions/68645). – Ethan Furman May 10 '17 at 20:46

2 Answers2

4

Unless you do something to change how attribute assignment works (with __setattr__ or descriptors), assigning to some_object.some_attribute always assigns to an instance attribute, even if there was already a class attribute with that name.

Thus, when you do

a = Test()

a.stat is the class attribute. But after you do

a.stat = 2

a.stat now refers to the instance attribute. The class attribute is unchanged.

user2357112
  • 260,549
  • 28
  • 431
  • 505
0

By

1
10

I assume you mean

0
10

since the class variable stat was never changed.

To answer your question, it does this because you added an instance member variable stat to the a object. Your objInstance.staticVar isn't a static variable at all, it's that new variable you added.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97