1

I am new in python i read about Instance variable:

A variable that is defined inside a method and belongs only to the current instance of a class.

So i test it:

Consider this code:

class test:
    count=0
    def __init__(self):
          test.count += 1

I have a class that add count after Instantiation. I run this:

t1=test() 
t1.count=100

and then I create new instance:

t2=test()
t2.count  # 2

then create another instance:

t3=test()
t3.count  # 3
t2.count  # 3

and then :

t1.count  # I get 100

My question is why t2 and t3 was update but if change value of instance variable of specific instance the instance 's instance variable was not update?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

2 Answers2

4

In t2 and t3, since you haven't defined an instance variable count, referring to, e.g., t2.count looks up the name in the class scope and evaluates to the class variable test.count.

In t1, you've created a completely different instance variable count that just happens to have the same name as the class variable. t1.count therefore returns this instance variable.

Wooble
  • 87,717
  • 12
  • 108
  • 131
2

Because instance attributes shadow class attributes, but they are independent.

When you try to access t2.count, there is no instance attribute (t2.__dict__ does not have a count key), so Python next looks at type(t2) to see if it can find the attribute there. The class does have such an attribute, so test.count is returned.

t1.count on the other hand finds the instance attribute and returns that. test.count is never considered.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343