Nikhil Rupanawar
Nikhil Rupanawar

Reputation: 4191

python: class variables and instance variables

How python recognize class and instance level variables ? are they different ?

For example,

class abc:
    i = 10
    def __init__(self, i):
        self.i = i


a = abc(30)
b = abc(40)
print a.i
print b.i
print abc.i

output
--------
30
40
10

Means, in above example when I access a.i (or b.i) and abc.i are they referring to completely different variables?

Upvotes: 0

Views: 73

Answers (3)

zhangyangyu
zhangyangyu

Reputation: 8610

First, your sample is wrong for you can not init the instance if there is only a self in the __init__.

>>> class abc:
...     i = 10
...     j = 11
...     def __init__(self, x):
...             self.i = x

Then, when you access the attribute on the instance, it will check the instance variables first. Refer the paragraph here. As you guess:

>>> a = abc(30)
>>> a.i
30
>>> a.j
11

Besides, the class variables is an object shared by all the instances, and instance variables are owned by the instance:

>>> class abc:
...     i = []
...     def __init__(self, x):
...             self.i = [x]
...             abc.i.append(x)
... 
>>> a = abc(30)
>>> b = abc(40)
>>> a.i
[30]
>>> b.i
[40]
>>> abc.i
[30, 40]

Upvotes: 2

Brionius
Brionius

Reputation: 14098

in above example when I access a.i (or b.i) and abc.i are they referring to completely different variables?

Yes.

abc.i is a Class Object reference.

a.i and b.i are each Instance Object references.

They are all separate references.

Upvotes: 2

sarwar
sarwar

Reputation: 2845

This is all assuming your init is meant to be:

def __init__(self,i):

Other wise it doesn't work. In the third case, abc.i the class hasn't been initialized so i acts as a static variable for which you set the value at 10 in the class definition. In the first two instances, when you called init you created an instance of abc with a specific i value. When you ask for the i value of each of those instances you get the correct number.

Upvotes: 1

Related Questions