Ganesh Satpute
Ganesh Satpute

Reputation: 3941

Python: Static variable (or, difference between class.some_var and inst.some_var)

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?

Upvotes: 2

Views: 260

Answers (2)

TigerhawkT3
TigerhawkT3

Reputation: 49318

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.

Upvotes: 0

user2357112
user2357112

Reputation: 280564

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.

Upvotes: 4

Related Questions