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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Anyone want to explain the downvote so I can fix the problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.