DEV Community

Distinguishing Instance Variables from Class Variables in python

Johnson Ogwuru on November 29, 2017

In the last article we learnt how to create a class and its instance. Today we would look at the difference between an instance variable and a cla...
Collapse
 
lildvlpr profile image
Nestor Zepeda

Thank you for doing these little tutorials! I'm just now learning python so I find these extremely helpful.

Collapse
 
ogwurujohnson profile image
Johnson Ogwuru

You re always welcome. I'm happy you find them helpful

Collapse
 
linomanzz profile image
linoman-zz

hello dear Johnson,

many thanks for the great introduction into instance variables and class variables.

this is extremely helpful and very very convincing tutorial and training.

one question though: would you do some tutorials in the same way - discussing the
corey materials in depth ...

eg the following:

Python OOP 2 - Class Variables - youtu.be/BJ-VvGyQxho
[you allready did it : Python OOP 3 - Classmethods and Staticmethods - youtu.be/rq8cL2XMM5M ]

Python OOP 4 - Inheritance - youtu.be/RSl87lqOXDE
Python OOP 5 - Special (Magic/Dunder) Methods - youtu.be/3ohzBxoFHAY
Python OOP 6 - Property Decorators - youtu.be/jCzT9XFZ5bw

that would be fantastic. Love to hear from you

greetings

Collapse
 
ogwurujohnson profile image
Johnson Ogwuru

Hello Linoman, i'm sorry i am replying a year after and you have probably gotten to understand those concepts, but thank you. I would try to write an article on those.

Collapse
 
geo5555 profile image
geo5555

this example is taken from Correy Schafer

Collapse
 
ogwurujohnson profile image
Johnson Ogwuru

Found it to be easier, to teach the concept discussed

Collapse
 
sagaryadav profile image
sagaryadav

Thank you Ogwuru for this article.
In the example, all the Instance Variables have self. appended to them whereas Class Variables don't. Is it like this or is it a coincidence?

Collapse
 
ogwurujohnson profile image
Johnson Ogwuru

Its not a coincidence

Collapse
 
cvasudev profile image
cvasudev

So in this case you have used class variable to store a constant however is there any other use case where we can use class variable instead of instance variable?

Collapse
 
ogwurujohnson profile image
Johnson Ogwuru • Edited

So whenever you need to create a variable that needs to be shared by all instances or methods in a class, then and only then it makes sense to use class variables