Python – Class Variable vs Instance Variables

Class variables vs instance variables could seem a bit strange, if you have no OOP experience, but after a few thausand lines of code they become logical. So, in around two days of programming you will be getting it intuitively 🙂

South Park, Sofia

Ok, let’s take a look at our FootballPlayer class, looking like this:

As the minimal salary in Bulgaria is currently 650 BGN, that is the minimal salary of every football player, upon creation. So, any player created will be created with this minimal salary. In the example below, I am creating two football player instances – vitosh  and joe. Without assigning them any min_salary , they get the one from the class, automatically assigned to them:

If we change the class variable min_salary, then the property is changed for every instance, including the already created ones:

And it makes sense. What also makes sense (but only for some people), is that we may use the __class__ dunder of a given instance, to change the class variable:

Enjoy!

Tagged with: , , ,