Class variable in python

What?

class A(object):
    inst = 1

inst is the class variable

Is class variable shared across the instances?

Yes. but no.

Usually, in object oriented languages like c++, java, the class variables are shared across instances. But here something different.

Watch the below examples and output

class variables are shared across instances in some sense.

In [70]: class A(object):
    ...:     inst = 1
    ...:     

In [71]: 

In [71]: a = A()

In [72]: b = A()

In [73]: a.inst
Out[73]: 1

In [74]: b.inst
Out[74]: 1

In [75]: A
Out[75]: __main__.A

In [76]: A.inst = 22

In [77]: a.inst
Out[77]: 22

In [78]: b.inst
Out[78]: 22

in the above sample, the change A.inst = 22 reflect across all instances a,b.

But What happens here?

In [79]: class A(object):
    ...:     inst = 1
    ...:     

In [80]: a = A()

In [81]: b = A()

In [82]: a.inst = 3     # Notice here this is the culprit

In [83]: b.inst
Out[83]: 1

In [84]: A.inst = 5     # Change in class variable

In [85]: b.inst
Out[85]: 5

In [86]: a.inst
Out[86]: 3  # Why this did not get update?

line no: 82 is the important change. Our usual understanding is, the class variable can be accessed via instance or class name. So, we can change the class varialbe via instance also. This will update entirely. It is absolutely wrong. Since, when you change the class variable’s value by instance, the scope gets changed.

a.inst = 3 means, one instance specific attribute is created dynamically which is reserved for this particular instance. So, a.inst is not exactly looking for class variable if instance attribute existing.

Then, How can we access the class variable?

just try it like below

a.__class__.inst

you should be getting latest class variable value which is 5 in our case.

This lack of understanding may cost one opportunity. Lets be aware.

Advertisements

About Navaneethan

mixed feelings...
This entry was posted in Academic, General, Python. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s